diff --git a/e-commerce/node_modules/next-intl-swc-plugin-extractor/LICENSE b/e-commerce/node_modules/next-intl-swc-plugin-extractor/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..118a41c4ade24a7712b4c8e7d7a72851f03c3d94 --- /dev/null +++ b/e-commerce/node_modules/next-intl-swc-plugin-extractor/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jan Amann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/e-commerce/node_modules/next-intl-swc-plugin-extractor/README.md b/e-commerce/node_modules/next-intl-swc-plugin-extractor/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0e54fe583ffb133d16b8a0d74071798e53ed0516 --- /dev/null +++ b/e-commerce/node_modules/next-intl-swc-plugin-extractor/README.md @@ -0,0 +1,5 @@ +# next-intl-swc-plugin-extractor + +SWC plugin for extracting inline messages. + +**Important:** This package is only intended for internal use and it's API may change at any time. diff --git a/e-commerce/node_modules/next-intl-swc-plugin-extractor/package.json b/e-commerce/node_modules/next-intl-swc-plugin-extractor/package.json new file mode 100644 index 0000000000000000000000000000000000000000..27ab100c4c837fcee8ba8b15dad3c6c0a3d13562 --- /dev/null +++ b/e-commerce/node_modules/next-intl-swc-plugin-extractor/package.json @@ -0,0 +1,26 @@ +{ + "name": "next-intl-swc-plugin-extractor", + "version": "4.14.9", + "sideEffects": false, + "author": "Jan Amann ", + "contributors": [ + "강동윤 " + ], + "description": "SWC plugin for extracting inline messages.", + "license": "MIT", + "homepage": "https://next-intl.dev", + "repository": { + "type": "git", + "url": "git+https://github.com/amannn/next-intl.git" + }, + "scripts": { + "prepublishOnly": "turbo build", + "test": "cargo test --release", + "build": "cargo build --release --target wasm32-wasip1 --target-dir target" + }, + "main": "target/wasm32-wasip1/release/swc_plugin_extractor.wasm", + "files": [ + "target/wasm32-wasip1/release/swc_plugin_extractor.wasm" + ], + "gitHead": "b9fc98a814957b9c97894c7b57151215ac39afa6" +} diff --git a/e-commerce/node_modules/next-intl-swc-plugin-extractor/target/wasm32-wasip1/release/swc_plugin_extractor.wasm b/e-commerce/node_modules/next-intl-swc-plugin-extractor/target/wasm32-wasip1/release/swc_plugin_extractor.wasm new file mode 100644 index 0000000000000000000000000000000000000000..fcf72c8ac0d7d05ad701da9090fc66299af3502a --- /dev/null +++ b/e-commerce/node_modules/next-intl-swc-plugin-extractor/target/wasm32-wasip1/release/swc_plugin_extractor.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe1a1051266f0e28e75d123b88d9bd170a7ea26c568ef9e2fcf5e577ba19af40 +size 1269847 diff --git a/e-commerce/node_modules/next-intl/LICENSE b/e-commerce/node_modules/next-intl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..118a41c4ade24a7712b4c8e7d7a72851f03c3d94 --- /dev/null +++ b/e-commerce/node_modules/next-intl/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jan Amann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/e-commerce/node_modules/next-intl/README.md b/e-commerce/node_modules/next-intl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a9a8697771aefc19839e2ac7f972f474044efe60 --- /dev/null +++ b/e-commerce/node_modules/next-intl/README.md @@ -0,0 +1,99 @@ +

+
+ + + + + next-intl + + +
+
+

+ +Internationalization for Next.js. + +## Features + +Internationalization (i18n) is an essential part of the user experience, therefore `next-intl` gives you all the parts you need to get language nuances right. + +- 🌟 **ICU message syntax**: Localize your messages with interpolation, cardinal & ordinal plurals, enum-based label selection and rich text. +- 📅 **Dates, times & numbers**: Apply appropriate formatting without worrying about server/client differences like time zones. +- ✅ **Type-safe**: Speed up development with autocompletion for message keys and catch typos early with compile-time checks. +- 💡 **Hooks-based API**: Learn a single API that can be used across your code base to turn translations into plain strings or rich text. +- 🚀 **Next.js-native and performance-obsessed**: App Router, Server Components, static rendering—pick the right tool for the right job, next-intl works everywhere. +- 🌍 **Internationalized routing**: Provide unique pathnames per language and optionally localize pathnames for search engine optimization. + +[→ Read the docs](https://next-intl.dev) + +## What does it look like? + +```jsx +// UserProfile.tsx +import {useTranslations} from 'next-intl'; + +export default function UserProfile({user}) { + const t = useTranslations('UserProfile'); + + return ( +
+

{t('title', {firstName: user.firstName})}

+

{t('membership', {memberSince: user.memberSince})}

+

{t('followers', {count: user.numFollowers})}

+
+ ); +} +``` + +```js +// en.json +{ + "UserProfile": { + "title": "{firstName}'s profile", + "membership": "Member since {memberSince, date, short}", + "followers": "{count, plural, ↵ + =0 {No followers yet} ↵ + =1 {One follower} ↵ + other {# followers} ↵ + }" + } +} +``` + +## Lint your messages + +As an app grows, messages may drift and become inconsistent. + +A companion tool, [`eloqnt/cli`](https://cli.eloqnt.dev/docs), catches this by analyzing your source code and messages statically: + +```console +$ eloqnt lint + +messages/de.json +│ +│ "UserProfile.title": "Dein Profil" +│ ─┬────────── +│ ╰─ Inconsistent ICU arguments: missing {firstName} (inconsistent-args) +│ +│ "UserProfile.membership": "Member since {memberSince, date, short}" +│ ─┬────────────────────── +│ ╰─ Missing translation for de (missing-translation) + +✗ 1 error +! 1 warning + +→ Rule details: https://cli.eloqnt.dev/docs/lint-rules/ +→ Run `eloqnt translate` to fill in 1 missing translation +``` + +It can optionally also fill in missing translations with [`eloqnt translate`](https://cli.eloqnt.dev/docs/cli/translate), using your source code as context. + +--- + +
+ + Crowdin logo + +
+

Hosted on Vercel

+
diff --git a/e-commerce/node_modules/next-intl/config.d.ts b/e-commerce/node_modules/next-intl/config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..18460a6fc27541e6164344fa9cb94b5a5faa1d8a --- /dev/null +++ b/e-commerce/node_modules/next-intl/config.d.ts @@ -0,0 +1,4 @@ +// Needed for projects with `moduleResolution: 'node'` +import config from './dist/types/config'; + +export default config; diff --git a/e-commerce/node_modules/next-intl/dist/cjs/development/BuiltInPoCodec-B6w-kmTx.cjs b/e-commerce/node_modules/next-intl/dist/cjs/development/BuiltInPoCodec-B6w-kmTx.cjs new file mode 100644 index 0000000000000000000000000000000000000000..87d6234207cd4f1574b8143b967f47eb3c9ff291 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/cjs/development/BuiltInPoCodec-B6w-kmTx.cjs @@ -0,0 +1,34 @@ +'use strict'; + +var createPoCodec = require('@eloqnt/format-po'); + +function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; } + +var createPoCodec__default = /*#__PURE__*/_interopDefaultCompat(createPoCodec); + +// Derived from `@eloqnt/config`, so next-intl and eloqnt pass identical +// options to codecs. + +function defineCodec(factory) { + return factory; +} + +// `@eloqnt/format-po`, guarded so catalogs in the previous key-based layout +// fail loudly. Custom codecs referencing the package directly opt out. +var BuiltInPoCodec = defineCodec(() => { + const codec = createPoCodec__default.default(); + function assertMigrated(content) { + if (content.includes('X-Crowdin-SourceKey: msgstr')) { + throw new Error('This catalog uses the previous PO layout of next-intl, which stored message keys in `msgid`. The PO format now follows the gettext convention: the source text in `msgid` and the message key in `msgctxt`. Please migrate your catalogs, or use a custom codec to keep the previous layout: https://github.com/amannn/next-intl/pull/2393'); + } + } + return { + ...codec, + decode(content, context) { + assertMigrated(content); + return codec.decode(content, context); + } + }; +}); + +exports.default = BuiltInPoCodec; diff --git a/e-commerce/node_modules/next-intl/dist/cjs/development/plugin.cjs b/e-commerce/node_modules/next-intl/dist/cjs/development/plugin.cjs new file mode 100644 index 0000000000000000000000000000000000000000..9a8b8e8d3ad958d1d4f4e91021191122e23ad13c --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/cjs/development/plugin.cjs @@ -0,0 +1,1637 @@ +'use strict'; + +var fs$1 = require('fs/promises'); +var path = require('path'); +var module$1 = require('module'); +var url = require('url'); +var watcher = require('@parcel/watcher'); +var fs = require('fs'); +var core = require('@swc/core'); + +var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; +function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; } + +var fs__default$1 = /*#__PURE__*/_interopDefaultCompat(fs$1); +var path__default = /*#__PURE__*/_interopDefaultCompat(path); +var fs__default = /*#__PURE__*/_interopDefaultCompat(fs); + +function formatMessage(message) { + return `\n[next-intl] ${message}\n`; +} +function throwError(message) { + throw new Error(formatMessage(message)); +} +function warn(message) { + console.warn(formatMessage(message)); +} + +/** + * Returns a function that runs the provided callback only once per process. + * Next.js can call the config multiple times - this ensures we only run once. + * Uses an environment variable to track execution across config loads. + */ +function once(namespace) { + return function runOnce(fn) { + if (process.env[namespace] === '1') { + return; + } + process.env[namespace] = '1'; + fn(); + }; +} + +function stripTrailingSlash(dirPath) { + if (dirPath.endsWith('/')) { + return dirPath.slice(0, -1); + } else { + return dirPath; + } +} +function normalizeMessagesCatalogPaths(messagesPath) { + const rawPaths = Array.isArray(messagesPath) ? messagesPath : [messagesPath]; + return rawPaths.map(dirPath => stripTrailingSlash(String(dirPath).trim())).filter(dirPath => dirPath.length > 0); +} +function normalizeExtractorConfig(input) { + if (input.messages == null) { + throwError('`messages` is required when extracting messages.'); + } + const extract = input.extract; + let extractPath; + let sourceLocale; + if (extract !== undefined && extract !== true) { + if (extract.sourceLocale) { + warn('`extract.sourceLocale` is deprecated in favor of `messages.sourceLocale`.'); + sourceLocale = extract.sourceLocale; + } + if (extract.path) { + extractPath = stripTrailingSlash(extract.path); + } + } + const locales = input.messages.locales; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!locales) { + throwError('`messages.locales` is required when extracting messages.'); + } + if (input.messages.sourceLocale) { + sourceLocale = input.messages.sourceLocale; + } + if (!sourceLocale) { + throwError('`messages.sourceLocale` is required when extracting messages.'); + } + const srcPath = input.srcPath; + if (srcPath == null) { + throwError('`srcPath` is required when extracting messages.'); + } + const pathIsArray = Array.isArray(input.messages.path); + const messagesPath = normalizeMessagesCatalogPaths(input.messages.path); + if (messagesPath.length === 0) { + throwError('`messages.path` must not be empty.'); + } + if (extractPath == null) { + if (pathIsArray) { + throwError('When `messages.path` is an array, `extract.path` is required to select the writable catalog directory.'); + } + extractPath = messagesPath[0]; + } + return { + extract: { + locales, + path: extractPath, + sourceLocale, + srcPath + }, + messages: { + format: input.messages.format, + path: messagesPath + } + }; +} + +/** + * Wrapper around `fs.watch` that provides a workaround + * for https://github.com/nodejs/node/issues/5039. + */ +function watchFile(filepath, callback) { + const directory = path__default.default.dirname(filepath); + const filename = path__default.default.basename(filepath); + return fs__default.default.watch(directory, { + persistent: false, + recursive: false + }, (event, changedFilename) => { + if (changedFilename === filename) { + callback(); + } + }); +} + +const runOnce$1 = once('_NEXT_INTL_COMPILE_MESSAGES'); +function createMessagesDeclaration(messagesPaths) { + // Instead of running _only_ in certain cases, it's + // safer to _avoid_ running for certain known cases. + // https://github.com/amannn/next-intl/issues/2006 + const shouldBailOut = ['info', 'start' + + // Note: These commands don't consult the + // Next.js config, so we can't detect them here. + // - telemetry (however, the `detached-flush` DOES - see `createNextIntlPlugin`) + // - lint + // + // What remains are: + // - dev + // - build + // - typegen + ].some(arg => process.argv.includes(arg)); + if (shouldBailOut) { + return; + } + runOnce$1(() => { + for (const messagesPath of messagesPaths) { + const fullPath = path__default.default.resolve(messagesPath); + if (!fs__default.default.existsSync(fullPath)) { + throwError(`\`createMessagesDeclaration\` points to a non-existent file: ${fullPath}`); + } + if (!fullPath.endsWith('.json')) { + throwError(`\`createMessagesDeclaration\` needs to point to a JSON file. Received: ${fullPath}`); + } + + // Keep this as a runtime check and don't replace + // this with a constant during the build process + const env = process.env['NODE_ENV'.trim()]; + compileDeclaration(messagesPath); + if (env === 'development') { + startWatching(messagesPath); + } + } + }); +} +function startWatching(messagesPath) { + const watcher = watchFile(messagesPath, () => { + compileDeclaration(messagesPath, true); + }); + process.on('exit', () => { + watcher.close(); + }); +} +function compileDeclaration(messagesPath, async = false) { + const declarationPath = messagesPath.replace(/\.json$/, '.d.json.ts'); + function createDeclaration(content) { + return `// This file is auto-generated by next-intl, do not edit directly. +// See: https://next-intl.dev/docs/workflows/typescript#messages-arguments + +declare const messages: ${content.trim()}; +export default messages;`; + } + if (async) { + return fs__default.default.promises.readFile(messagesPath, 'utf-8').then(content => fs__default.default.promises.writeFile(declarationPath, createDeclaration(content))); + } + const content = fs__default.default.readFileSync(messagesPath, 'utf-8'); + fs__default.default.writeFileSync(declarationPath, createDeclaration(content)); +} + +const formats = { + json: { + codec: () => import('@eloqnt/format-json'), + extension: '.json' + }, + po: { + codec: () => Promise.resolve().then(function () { return require('./BuiltInPoCodec-B6w-kmTx.cjs'); }), + extension: '.po' + } +}; +function isBuiltInFormat(format) { + return typeof format === 'string' && format in formats; +} +function getFormatExtension(format) { + if (isBuiltInFormat(format)) { + return formats[format].extension; + } else { + return format.extension; + } +} +async function resolveCodec(format, projectRoot) { + if (isBuiltInFormat(format)) { + const factory = (await formats[format].codec()).default; + return factory(); + } else { + // A codec that starts with `.` or a filesystem root is a file path; + // everything else reads as a package specifier, mirroring how imports + // distinguish the two. Packages resolve from the project's dependencies. + const isPath = format.codec.startsWith('.') || path__default.default.isAbsolute(format.codec); + let resolvedPath; + if (isPath) { + resolvedPath = path__default.default.resolve(projectRoot, format.codec); + } else { + try { + resolvedPath = module$1.createRequire(path__default.default.join(projectRoot, 'noop.js')).resolve(format.codec); + } catch (error) { + throwError(`Could not resolve the codec package "${format.codec}". Is it installed?\n${error}`); + } + } + let module; + try { + module = await import(url.pathToFileURL(resolvedPath).href); + } catch (error) { + throwError(`Could not load codec from "${resolvedPath}".\n${error}`); + } + const factory = module.default; + if (!factory || typeof factory !== 'function') { + throwError(`Codec at "${resolvedPath}" must have a default export returned from \`defineCodec\`.`); + } + return factory(); + } +} + +class SourceFileFilter { + static EXTENSIONS = ['ts', 'tsx', 'js', 'jsx']; + + // Will not be entered, except if explicitly asked for + // TODO: At some point we should infer these from .gitignore + static IGNORED_DIRECTORIES = ['node_modules', '.next', '.git']; + static isSourceFile(filePath) { + const ext = path__default.default.extname(filePath); + return SourceFileFilter.EXTENSIONS.map(cur => '.' + cur).includes(ext); + } + static shouldEnterDirectory(dirPath, srcPaths) { + const dirName = path__default.default.basename(dirPath); + if (SourceFileFilter.IGNORED_DIRECTORIES.includes(dirName)) { + return SourceFileFilter.isIgnoredDirectoryExplicitlyIncluded(dirPath, srcPaths); + } + return true; + } + static isIgnoredDirectoryExplicitlyIncluded(ignoredDirPath, srcPaths) { + return srcPaths.some(srcPath => SourceFileFilter.isWithinPath(srcPath, ignoredDirPath)); + } + static isWithinPath(targetPath, basePath) { + const relativePath = path__default.default.relative(basePath, targetPath); + return relativePath === '' || !relativePath.startsWith('..'); + } +} + +class SourceFileScanner { + static async walkSourceFiles(dir, srcPaths, acc = []) { + const entries = await fs__default$1.default.readdir(dir, { + withFileTypes: true + }); + for (const entry of entries) { + const entryPath = path__default.default.join(dir, entry.name); + if (entry.isDirectory()) { + if (!SourceFileFilter.shouldEnterDirectory(entryPath, srcPaths)) { + continue; + } + await SourceFileScanner.walkSourceFiles(entryPath, srcPaths, acc); + } else { + if (SourceFileFilter.isSourceFile(entry.name)) { + acc.push(entryPath); + } + } + } + return acc; + } + static async getSourceFiles(srcPaths) { + const files = (await Promise.all(srcPaths.map(srcPath => SourceFileScanner.walkSourceFiles(srcPath, srcPaths)))).flat(); + return new Set(files); + } +} + +class SourceFileWatcher { + subscriptions = []; + constructor(roots, onChange) { + this.roots = roots; + this.onChange = onChange; + } + async start() { + if (this.subscriptions.length > 0) { + return; + } + const ignore = SourceFileFilter.IGNORED_DIRECTORIES.map(dir => `**/${dir}/**`); + for (const root of this.roots) { + const sub = await watcher.subscribe(root, async (err, events) => { + if (err) { + console.error(err); + return; + } + const filtered = await this.normalizeEvents(events); + if (filtered.length > 0) { + await this.onChange(filtered); + } + }, { + ignore + }); + this.subscriptions.push(sub); + } + } + async normalizeEvents(events) { + const directoryCreatePaths = []; + const otherEvents = []; + + // We need to expand directory creates because during rename operations, + // @parcel/watcher emits a directory create event but may not emit individual + // file events for the moved files + await Promise.all(events.map(async event => { + if (event.type === 'create') { + try { + const stats = await fs__default$1.default.stat(event.path); + if (stats.isDirectory()) { + directoryCreatePaths.push(event.path); + return; + } + } catch { + // Path doesn't exist or is inaccessible, treat as file + } + } + otherEvents.push(event); + })); + + // Expand directory create events to find source files inside + let expandedCreateEvents = []; + if (directoryCreatePaths.length > 0) { + try { + const sourceFiles = await SourceFileScanner.getSourceFiles(directoryCreatePaths); + expandedCreateEvents = Array.from(sourceFiles).map(filePath => ({ + type: 'create', + path: filePath + })); + } catch { + // Directories might have been deleted or are inaccessible + } + } + + // Combine original events with expanded directory creates. + // Deduplicate by path to avoid processing the same file twice + // in case @parcel/watcher also emitted individual file events. + const allEvents = [...otherEvents, ...expandedCreateEvents]; + const seenPaths = new Set(); + const deduplicated = []; + for (const event of allEvents) { + const key = `${event.type}:${event.path}`; + if (!seenPaths.has(key)) { + seenPaths.add(key); + deduplicated.push(event); + } + } + return deduplicated.filter(event => { + // Keep all delete events (might be deleted directories that no longer exist) + if (event.type === 'delete') { + return true; + } + // Keep source files + return SourceFileFilter.isSourceFile(event.path); + }); + } + async expandDirectoryDeleteEvents(events, prevKnownFiles) { + const expanded = []; + for (const event of events) { + if (event.type === 'delete' && !SourceFileFilter.isSourceFile(event.path)) { + const dirPath = path__default.default.resolve(event.path); + const filesInDirectory = []; + for (const filePath of prevKnownFiles) { + if (SourceFileFilter.isWithinPath(filePath, dirPath)) { + filesInDirectory.push(filePath); + } + } + + // If we found files within this path, it was a directory + if (filesInDirectory.length > 0) { + for (const filePath of filesInDirectory) { + expanded.push({ + type: 'delete', + path: filePath + }); + } + } else { + // Not a directory or no files in it, pass through as-is + expanded.push(event); + } + } else { + // Pass through as-is + expanded.push(event); + } + } + return expanded; + } + async stop() { + await Promise.all(this.subscriptions.map(sub => sub.unsubscribe())); + this.subscriptions = []; + } + [Symbol.dispose]() { + void this.stop(); + } +} + +function normalizePathToPosix(filePath) { + // `path.relative` uses OS-specific separators. For stable `.po` references we + // always use POSIX separators, regardless of the OS that ran extraction. + return path__default.default.posix.normalize(filePath.split(path__default.default.win32.sep).join(path__default.default.posix.sep)); +} +function hasLocalesToExtract(config) { + const { + locales + } = config.extract; + return locales === 'infer' || locales.length > 0; +} +function warnAboutMissingReferences(messages) { + const warnedIds = new Set(); + for (const message of messages) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (message.references[0] == null && !warnedIds.has(message.id)) { + warnedIds.add(message.id); + warn(`Missing file reference for extracted message: ${message.id}`); + } + } +} +function localeCompare(a, b) { + return a.localeCompare(b, 'en'); +} +function compareReferences(refA, refB) { + const pathCompare = localeCompare(refA.path, refB.path); + if (pathCompare !== 0) return pathCompare; + return (refA.line ?? 0) - (refB.line ?? 0) || (refA.column ?? 0) - (refB.column ?? 0); +} +function getDefaultProjectRoot() { + return process.cwd(); +} + +class CatalogLocales { + onChangeCallbacks = new Set(); + constructor(params) { + this.messagesDir = params.messagesDir; + this.sourceLocale = params.sourceLocale; + this.extension = params.extension; + this.locales = params.locales; + } + async getTargetLocales() { + if (this.targetLocales) { + return this.targetLocales; + } + if (this.locales === 'infer') { + this.targetLocales = await this.readTargetLocales(); + } else { + this.targetLocales = this.locales.filter(locale => locale !== this.sourceLocale); + } + return this.targetLocales; + } + async readTargetLocales() { + try { + const files = await fs__default$1.default.readdir(this.messagesDir); + return files.filter(file => file.endsWith(this.extension)).map(file => path__default.default.basename(file, this.extension)).filter(locale => locale !== this.sourceLocale); + } catch { + return []; + } + } + subscribeLocalesChange(callback) { + this.onChangeCallbacks.add(callback); + if (this.locales === 'infer' && !this.watcher) { + void this.startWatcher(); + } + } + unsubscribeLocalesChange(callback) { + this.onChangeCallbacks.delete(callback); + if (this.onChangeCallbacks.size === 0) { + this.stopWatcher(); + } + } + async startWatcher() { + if (this.watcher) { + return; + } + await fs__default$1.default.mkdir(this.messagesDir, { + recursive: true + }); + this.watcher = fs__default.default.watch(this.messagesDir, { + persistent: false, + recursive: false + }, (event, filename) => { + const isCatalogFile = filename != null && filename.endsWith(this.extension) && !filename.includes(path__default.default.sep); + if (isCatalogFile) { + void this.onChange(); + } + }); + } + stopWatcher() { + if (this.watcher) { + this.watcher.close(); + this.watcher = undefined; + } + } + async onChange() { + const oldLocales = new Set(this.targetLocales || []); + this.targetLocales = await this.readTargetLocales(); + const newLocalesSet = new Set(this.targetLocales); + const added = this.targetLocales.filter(locale => !oldLocales.has(locale)); + const removed = Array.from(oldLocales).filter(locale => !newLocalesSet.has(locale)); + if (added.length > 0 || removed.length > 0) { + for (const callback of this.onChangeCallbacks) { + callback({ + added, + removed + }); + } + } + } +} + +class CatalogPersister { + constructor(params) { + this.messagesPath = params.messagesPath; + this.codec = params.codec; + this.extension = params.extension; + this.sourceLocale = params.sourceLocale; + } + getFileName(locale) { + return locale + this.extension; + } + getFilePath(locale) { + return path__default.default.join(this.messagesPath, this.getFileName(locale)); + } + async read(locale) { + const filePath = this.getFilePath(locale); + let content; + try { + content = await fs__default$1.default.readFile(filePath, 'utf8'); + } catch (error) { + if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') { + return []; + } + throw new Error(`Error while reading ${this.getFileName(locale)}:\n> ${error}`, { + cause: error + }); + } + try { + const messages = this.codec.decode(content, { + locale, + sourceLocale: this.sourceLocale + }); + assertNoArrayMessages(messages); + return messages; + } catch (error) { + throw new Error(`Error while decoding ${this.getFileName(locale)}:\n> ${error}`, { + cause: error + }); + } + } + async write(messages, context) { + const filePath = this.getFilePath(context.locale); + warnAboutMissingReferences(messages); + const content = this.codec.encode(messages, context); + try { + const outputDir = path__default.default.dirname(filePath); + await fs__default$1.default.mkdir(outputDir, { + recursive: true + }); + await fs__default$1.default.writeFile(filePath, content); + } catch (error) { + console.error(`❌ Failed to write catalog: ${error}`); + } + } + async getLastModified(locale) { + const filePath = this.getFilePath(locale); + try { + const stats = await fs__default$1.default.stat(filePath); + return stats.mtime; + } catch { + return undefined; + } + } +} + +// The codecs read arrays fine (numeric path segments), but the runtime only +// supports strings — enforced here where the runtime's rules apply. +function assertNoArrayMessages(messages) { + for (const message of messages) { + const segments = message.segments; + if (!Array.isArray(segments)) continue; + const firstIndex = segments.findIndex(segment => typeof segment === 'number'); + if (firstIndex === -1) continue; + const arrayPath = segments.slice(0, firstIndex).join('.'); + throw new Error(`Message at \`${arrayPath}\` resolved to an array, but only strings are supported. See https://next-intl.dev/docs/usage/translations#arrays-of-messages`); + } +} + +/** + * De-duplicates excessive save invocations, + * while keeping a single one instant. + */ +class SaveScheduler { + isSaving = false; + pendingResolvers = []; + constructor(delayMs = 50) { + this.delayMs = delayMs; + } + async schedule(saveTask) { + return new Promise((resolve, reject) => { + this.pendingResolvers.push({ + resolve, + reject + }); + this.nextSaveTask = saveTask; + if (!this.isSaving && !this.saveTimeout) { + // Not currently saving and no scheduled save, save immediately + this.executeSave(); + } else if (this.saveTimeout) { + // A save is already scheduled, reschedule to debounce + this.scheduleSave(); + } + // If isSaving is true and no timeout is scheduled, the current save + // will check for pending resolvers when it completes and schedule + // another save if needed (see finally block in executeSave) + }); + } + scheduleSave() { + if (this.saveTimeout) { + clearTimeout(this.saveTimeout); + } + this.saveTimeout = setTimeout(() => { + this.saveTimeout = undefined; + this.executeSave(); + }, this.delayMs); + } + async executeSave() { + if (this.isSaving) { + return; + } + const saveTask = this.nextSaveTask; + if (!saveTask) { + return; + } + + // Capture current pending resolvers for this save + const resolversForThisSave = this.pendingResolvers; + this.pendingResolvers = []; + this.nextSaveTask = undefined; + this.isSaving = true; + try { + const result = await saveTask(); + + // Resolve only the promises that were pending when this save started + resolversForThisSave.forEach(({ + resolve + }) => resolve(result)); + } catch (error) { + // Reject only the promises that were pending when this save started + resolversForThisSave.forEach(({ + reject + }) => reject(error)); + } finally { + this.isSaving = false; + + // If new saves were requested during this save, schedule another + if (this.pendingResolvers.length > 0) { + this.scheduleSave(); + } + } + } + [Symbol.dispose]() { + if (this.saveTimeout) { + clearTimeout(this.saveTimeout); + this.saveTimeout = undefined; + } + this.pendingResolvers = []; + this.nextSaveTask = undefined; + this.isSaving = false; + } +} + +class CatalogManager { + /** + * Extraction-derived fields aggregated into `ExtractorMessage`. + * Source code is the source of truth for these fields, only ancillary + * codec fields may merge from disk (e.g. flags). + */ + static extractorOwnedAggregatorKeys = new Set(['description', 'id', 'message', 'references']); + /** + * Source of truth for statically extracted source messages, + * grouped by file and message ID. + */ + sourceMessagesByFile = new Map(); + + /** + * Reverse index for rebuilding aggregated messages without scanning all files. + * Contains the same `SourceExtractedMessage` arrays as `sourceMessagesByFile` and is + * kept in sync with it. + */ + sourceMessagesById = new Map(); + + /** + * Fast lookup for messages by ID, aggregated across all files. This combines + * metadata from `sourceMessagesById`, e.g. references and descriptions. + */ + messagesById = new Map(); + + /** + * This potentially also includes outdated ones that were initially available, + * but are not used anymore. This allows to restore them if they are used again. + **/ + translationsByTargetLocale = new Map(); + lastWriteByLocale = new Map(); + + // Cached instances + + // Resolves when all catalogs are loaded + + // Resolves when the initial project scan and processing is complete + + constructor(config, opts) { + this.config = config; + this.saveScheduler = new SaveScheduler(opts.saveDebounceMs ?? 50); + this.projectRoot = opts.projectRoot ?? getDefaultProjectRoot(); + this.isDevelopment = opts.isDevelopment ?? false; + this.extractor = opts.extractor; + if (this.isDevelopment) { + // We kick this off as early as possible, so we get notified about changes + // that happen during the initial project scan (while awaiting it to + // complete though) + this.sourceWatcher = new SourceFileWatcher(this.getSrcPaths(), this.handleFileEvents.bind(this)); + void this.sourceWatcher.start(); + } + } + async getCodec() { + if (!this.codec) { + this.codec = await resolveCodec(this.config.messages.format, this.projectRoot); + } + return this.codec; + } + async getPersister() { + if (this.persister) { + return this.persister; + } else { + this.persister = new CatalogPersister({ + messagesPath: this.config.extract.path, + codec: await this.getCodec(), + extension: getFormatExtension(this.config.messages.format), + sourceLocale: this.config.extract.sourceLocale + }); + return this.persister; + } + } + getCatalogLocales() { + if (this.catalogLocales) { + return this.catalogLocales; + } else { + const messagesDir = path__default.default.join(this.projectRoot, this.config.extract.path); + this.catalogLocales = new CatalogLocales({ + messagesDir, + extension: getFormatExtension(this.config.messages.format), + locales: this.config.extract.locales, + sourceLocale: this.config.extract.sourceLocale + }); + return this.catalogLocales; + } + } + async getTargetLocales() { + return this.getCatalogLocales().getTargetLocales(); + } + getSrcPaths() { + return (Array.isArray(this.config.extract.srcPath) ? this.config.extract.srcPath : [this.config.extract.srcPath]).map(srcPath => path__default.default.join(this.projectRoot, srcPath)); + } + async loadMessages() { + const sourceDiskMessages = await this.loadSourceMessages(); + this.loadCatalogsPromise = this.loadTargetMessages(); + await this.loadCatalogsPromise; + this.scanCompletePromise = (async () => { + const sourceFiles = Array.from(await SourceFileScanner.getSourceFiles(this.getSrcPaths())) + // Stable file order keeps catalog ties independent of processing timing + .toSorted(localeCompare); + const extractedFiles = await Promise.all(sourceFiles.map(async filePath => ({ + filePath, + messages: await this.extractFile(filePath) + }))); + for (const { + filePath, + messages + } of extractedFiles) { + if (messages) { + this.applyFileMessages(filePath, messages); + } + } + this.mergeSourceDiskMetadata(sourceDiskMessages); + })(); + await this.scanCompletePromise; + if (this.isDevelopment) { + const catalogLocales = this.getCatalogLocales(); + catalogLocales.subscribeLocalesChange(this.onLocalesChange); + } + } + async loadSourceMessages() { + // Load source catalog to hydrate metadata (e.g. flags) later without + // treating catalog entries as source of truth. + const diskMessages = await this.loadLocaleMessages(this.config.extract.sourceLocale); + const byId = new Map(); + for (const diskMessage of diskMessages) { + byId.set(diskMessage.id, diskMessage); + } + return byId; + } + async loadLocaleMessages(locale) { + const persister = await this.getPersister(); + const messages = await persister.read(locale); + const fileTime = await persister.getLastModified(locale); + this.lastWriteByLocale.set(locale, fileTime); + return messages; + } + async loadTargetMessages() { + const targetLocales = await this.getTargetLocales(); + await Promise.all(targetLocales.map(locale => this.reloadLocaleCatalog(locale))); + } + async reloadLocaleCatalog(locale) { + const diskMessages = await this.loadLocaleMessages(locale); + if (locale === this.config.extract.sourceLocale) { + // For source: Merge additional properties like flags + for (const diskMessage of diskMessages) { + const prev = this.messagesById.get(diskMessage.id); + if (prev) { + for (const key of Object.keys(diskMessage)) { + if (!CatalogManager.extractorOwnedAggregatorKeys.has(key)) { + // For unknown properties (like flags), disk wins + prev[key] = diskMessage[key]; + } + } + } + } + } else { + // For target: disk wins completely, BUT preserve existing translations + // if we read empty (likely a write in progress by an external tool + // that causes the file to temporarily be empty) + const existingTranslations = this.translationsByTargetLocale.get(locale); + const hasExistingTranslations = existingTranslations && existingTranslations.size > 0; + if (diskMessages.length > 0) { + // We got content from disk, replace with it + const translations = new Map(); + for (const message of diskMessages) { + translations.set(message.id, message); + } + this.translationsByTargetLocale.set(locale, translations); + } else if (hasExistingTranslations) ; else { + // We read empty and have no existing translations + const translations = new Map(); + this.translationsByTargetLocale.set(locale, translations); + } + } + } + mergeSourceDiskMetadata(diskMessages) { + for (const [id, diskMessage] of diskMessages) { + const existing = this.messagesById.get(id); + if (!existing) continue; + + // Fill unknown metadata from disk without replacing extraction-owned fields. + for (const key of Object.keys(diskMessage)) { + if (!CatalogManager.extractorOwnedAggregatorKeys.has(key) && existing[key] == null) { + existing[key] = diskMessage[key]; + } + } + } + } + async processFile(absoluteFilePath) { + const messages = await this.extractFile(absoluteFilePath); + + // `undefined` only when `extractFile()` throws. An empty array is success + // and must still run `applyFileMessages` to clear stale ids for this file. + if (!messages) return false; + return this.applyFileMessages(absoluteFilePath, messages); + } + async extractFile(absoluteFilePath) { + let messages = []; + try { + const content = await fs__default$1.default.readFile(absoluteFilePath, 'utf8'); + let extraction; + try { + extraction = await this.extractor.extract(absoluteFilePath, content); + } catch { + return undefined; + } + messages = extraction.messages; + } catch (err) { + if (err.code !== 'ENOENT') { + throw err; + } + // ENOENT -> treat as no messages + } + return messages; + } + applyFileMessages(absoluteFilePath, messages) { + const prevFileMessages = this.sourceMessagesByFile.get(absoluteFilePath); + const nextFileMessages = this.groupSourceMessagesById(messages); + const affectedIds = new Set([...(prevFileMessages?.keys() ?? []), ...nextFileMessages.keys()]); + if (nextFileMessages.size > 0) { + this.sourceMessagesByFile.set(absoluteFilePath, nextFileMessages); + } else { + this.sourceMessagesByFile.delete(absoluteFilePath); + } + + // Clear this file's contribution from the reverse index, then re-insert + // fresh rows and rebuild aggregates (messagesById) per touched id. + for (const id of affectedIds) { + const sourceMessagesForId = this.sourceMessagesById.get(id); + if (sourceMessagesForId) { + sourceMessagesForId.delete(absoluteFilePath); + // No files left for this id: drop the reverse-index entry. + if (sourceMessagesForId.size === 0) { + this.sourceMessagesById.delete(id); + } + } + const nextSourceMessagesForId = nextFileMessages.get(id); + if (nextSourceMessagesForId) { + let sourceMessagesByFile = this.sourceMessagesById.get(id); + if (!sourceMessagesByFile) { + sourceMessagesByFile = new Map(); + this.sourceMessagesById.set(id, sourceMessagesByFile); + } + sourceMessagesByFile.set(absoluteFilePath, nextSourceMessagesForId); + } + this.rebuildMessageById(id); + } + const changed = this.haveMessagesChangedForFile(prevFileMessages, nextFileMessages); + return changed; + } + groupSourceMessagesById(messages) { + const result = new Map(); + for (const message of messages) { + const messagesById = result.get(message.id); + if (messagesById) { + messagesById.push(message); + } else { + result.set(message.id, [message]); + } + } + return result; + } + rebuildMessageById(id) { + const sourceMessages = Array.from(this.sourceMessagesById.get(id)?.values() ?? []).flat(); + if (sourceMessages.length === 0) { + this.messagesById.delete(id); + return; + } + const previousMessage = this.messagesById.get(id); + const aggregate = { + description: this.mergeDescriptions(sourceMessages), + id, + message: sourceMessages[0].message, + references: sourceMessages.map(message => message.reference).sort(compareReferences) + }; + if (previousMessage) { + for (const key of Object.keys(previousMessage)) { + // Preserve extra fields (e.g. from disk/codec) across rebuilds; the + // four core fields above are always recomputed from source messages. + if (!CatalogManager.extractorOwnedAggregatorKeys.has(key) && aggregate[key] == null) { + aggregate[key] = previousMessage[key]; + } + } + } + this.messagesById.set(id, aggregate); + } + mergeDescriptions(messages) { + const sortedByReference = messages.toSorted((a, b) => compareReferences(a.reference, b.reference)); + const merged = []; + for (const message of sortedByReference) { + const { + description + } = message; + if (description != null && !merged.includes(description)) { + merged.push(description); + } + } + return merged; + } + haveMessagesChangedForFile(beforeMessages, afterMessages) { + // If one exists and the other doesn't, there's a change + if (!beforeMessages) { + return afterMessages.size > 0; + } + + // Different sizes means changes + if (beforeMessages.size !== afterMessages.size) { + return true; + } + + // Check differences in beforeMessages vs afterMessages + for (const [id, prevSourceMessages] of beforeMessages) { + const nextSourceMessages = afterMessages.get(id); + if (!nextSourceMessages) { + return true; + } + if (!this.areSourceMessageArraysEqual(prevSourceMessages, nextSourceMessages)) { + return true; // Early exit on first difference + } + } + return false; + } + areSourceMessageArraysEqual(messages1, messages2) { + return messages1.length === messages2.length && messages1.every((message, index) => this.areSourceMessagesEqual(message, messages2[index])); + } + areSourceMessagesEqual(msg1, msg2) { + return msg1.id === msg2.id && msg1.message === msg2.message && msg1.description === msg2.description && msg1.reference.path === msg2.reference.path && msg1.reference.line === msg2.reference.line && msg1.reference.column === msg2.reference.column; + } + async save() { + return this.saveScheduler.schedule(() => this.saveImpl()); + } + async saveImpl() { + await this.saveLocale(this.config.extract.sourceLocale); + const targetLocales = await this.getTargetLocales(); + await Promise.all(targetLocales.map(locale => this.saveLocale(locale))); + } + async saveLocale(locale) { + await this.loadCatalogsPromise; + const messages = Array.from(this.messagesById.values()); + const persister = await this.getPersister(); + const isSourceLocale = locale === this.config.extract.sourceLocale; + + // Check if file was modified externally (poll-at-save is cheaper than + // watchers here since stat() is fast and avoids continuous overhead) + const lastWriteTime = this.lastWriteByLocale.get(locale); + const currentFileTime = await persister.getLastModified(locale); + if (currentFileTime && lastWriteTime && currentFileTime > lastWriteTime) { + await this.reloadLocaleCatalog(locale); + } + const localeMessages = isSourceLocale ? this.messagesById : this.translationsByTargetLocale.get(locale); + const messagesToPersist = messages.map(message => { + const localeMessage = localeMessages?.get(message.id); + return { + ...localeMessage, + id: message.id, + description: message.description, + references: message.references, + message: isSourceLocale ? message.message : localeMessage?.message ?? '' + }; + }); + await persister.write(messagesToPersist, { + locale, + sourceMessagesById: this.messagesById + }); + + // Update timestamps + const newTime = await persister.getLastModified(locale); + this.lastWriteByLocale.set(locale, newTime); + } + onLocalesChange = async params => { + // Chain to existing promise + this.loadCatalogsPromise = Promise.all([this.loadCatalogsPromise, ...params.added.map(locale => this.reloadLocaleCatalog(locale))]); + for (const locale of params.added) { + await this.saveLocale(locale); + } + for (const locale of params.removed) { + this.translationsByTargetLocale.delete(locale); + this.lastWriteByLocale.delete(locale); + } + }; + async handleFileEvents(events) { + if (this.loadCatalogsPromise) { + await this.loadCatalogsPromise; + } + + // Wait for initial scan to complete to avoid race conditions + if (this.scanCompletePromise) { + await this.scanCompletePromise; + } + let changed = false; + const expandedEvents = await this.sourceWatcher.expandDirectoryDeleteEvents(events, Array.from(this.sourceMessagesByFile.keys())); + // Stable file order keeps catalog ties independent of event timing. + for (const event of expandedEvents.toSorted((a, b) => localeCompare(a.path, b.path))) { + const hasChanged = await this.processFile(event.path); + changed ||= hasChanged; + } + if (changed) { + await this.save(); + } + } + [Symbol.dispose]() { + this.sourceWatcher?.stop(); + this.sourceWatcher = undefined; + this.saveScheduler[Symbol.dispose](); + if (this.catalogLocales && this.isDevelopment) { + this.catalogLocales.unsubscribeLocalesChange(this.onLocalesChange); + } + } +} + +class LRUCache { + constructor(maxSize) { + this.maxSize = maxSize; + this.cache = new Map(); + } + set(key, value) { + const isNewKey = !this.cache.has(key); + if (isNewKey && this.cache.size >= this.maxSize) { + const lruKey = this.cache.keys().next().value; + if (lruKey !== undefined) { + this.cache.delete(lruKey); + } + } + this.cache.set(key, { + key, + value + }); + } + get(key) { + const item = this.cache.get(key); + if (item) { + this.cache.delete(key); + this.cache.set(key, item); + return item.value; + } + return undefined; + } +} + +const require$2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.cjs', document.baseURI).href))); +class MessageExtractor { + compileCache = new LRUCache(750); + constructor(opts) { + this.isDevelopment = opts.isDevelopment ?? false; + this.projectRoot = opts.projectRoot ?? getDefaultProjectRoot(); + this.sourceMap = opts.sourceMap ?? false; + } + async extract(absoluteFilePath, source) { + const cacheKey = [source, absoluteFilePath].join('!'); + const cached = this.compileCache.get(cacheKey); + if (cached) return cached; + + // Shortcut parsing if hook is not used. The Turbopack integration already + // pre-filters this, but for webpack this feature doesn't exist, so we need + // to do it here. + if (!source.includes('useExtracted') && !source.includes('getExtracted')) { + return { + messages: [], + code: source + }; + } + const filePath = normalizePathToPosix(path__default.default.relative(this.projectRoot, absoluteFilePath)); + const result = await core.transform(source, { + jsc: { + target: 'esnext', + parser: { + syntax: 'typescript', + tsx: true, + decorators: true + }, + experimental: { + cacheRoot: 'node_modules/.cache/swc', + disableBuiltinTransformsForInternalTesting: true, + disableAllLints: true, + plugins: [[require$2.resolve('next-intl-swc-plugin-extractor'), { + isDevelopment: this.isDevelopment, + filePath + }]] + } + }, + sourceMaps: this.sourceMap, + // Is converted into a relative path by Next.js when + // the final source map is generated + sourceFileName: absoluteFilePath, + filename: filePath + }); + + // TODO: Improve the typing of @swc/core + const output = result.output; + // The plugin emits a tagged union of extracted messages and + // `useTranslations` usages; this extractor only consumes the former. + const messages = JSON.parse(JSON.parse(output).results).filter(item => item.type === 'extracted').map(item => ({ + id: item.id, + message: item.message, + description: item.description, + reference: item.reference + })); + const extractionResult = { + code: result.code, + map: result.map, + messages + }; + this.compileCache.set(cacheKey, extractionResult); + return extractionResult; + } +} + +class ExtractionCompiler { + constructor(config, opts = {}) { + const extractor = opts.extractor ?? new MessageExtractor(opts); + this.manager = new CatalogManager(config, { + ...opts, + extractor + }); + this[Symbol.dispose] = this[Symbol.dispose].bind(this); + this.installExitHandlers(); + } + async extractAll() { + // We can't rely on all files being compiled (e.g. due to persistent + // caching), so loading the messages initially is necessary. + await this.manager.loadMessages(); + await this.manager.save(); + } + [Symbol.dispose]() { + this.uninstallExitHandlers(); + this.manager[Symbol.dispose](); + } + installExitHandlers() { + const cleanup = this[Symbol.dispose]; + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + } + uninstallExitHandlers() { + const cleanup = this[Symbol.dispose]; + process.off('exit', cleanup); + process.off('SIGINT', cleanup); + process.off('SIGTERM', cleanup); + } +} + +// Avoid rollup's `replace` plugin to compile this away +const nodeEnvKey = 'NODE_ENV'.trim(); + +// We avoid reading `argv.includes('dev')` related to +// https://github.com/amannn/next-intl/issues/2006 +const isDevelopment = process.env[nodeEnvKey] === 'development'; +const isNextBuild = process.argv.includes('build'); +const isDevelopmentOrNextBuild = isDevelopment || isNextBuild; + +// Single compiler instance, initialized once per process +let compiler; +const runOnce = once('_NEXT_INTL_EXTRACT'); +function initExtractionCompiler(extractorConfig) { + if (!extractorConfig || !hasLocalesToExtract(extractorConfig)) { + return; + } + + // Avoid running for: + // - info + // - start + // - typegen + // + // Doesn't consult Next.js config anyway: + // - lint + // - telemetry (however, the `detached-flush` DOES - see `createNextIntlPlugin`) + // + // What remains are: + // - dev (NODE_ENV=development) + // - build (NODE_ENV=production) + const shouldRun = isDevelopment || isNextBuild; + if (!shouldRun) return; + runOnce(() => { + compiler = new ExtractionCompiler(extractorConfig, { + isDevelopment, + projectRoot: process.cwd() + }); + + // Fire-and-forget: Start extraction, don't block config return. + // In dev mode, this also starts the file watcher. + // In prod, ideally we would wait until the extraction is complete, + // but we can't `await` anywhere (at least for Turbopack). + // The result is ok though, as if we encounter untranslated messages, + // we'll simply add empty messages to the catalog. So for actually + // running the app, there is no difference. + compiler.extractAll(); + function cleanup() { + if (compiler) { + compiler[Symbol.dispose](); + compiler = undefined; + } + } + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + }); +} + +function getCurrentVersion() { + try { + const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.cjs', document.baseURI).href))); + const pkg = require$1('next/package.json'); + return pkg.version; + } catch (error) { + throw new Error('Failed to get current Next.js version. This can happen if next-intl/plugin is imported into your app code outside of your next.config.js.', { + cause: error + }); + } +} +function compareVersions(version1, version2) { + const v1Parts = version1.split('.').map(Number); + const v2Parts = version2.split('.').map(Number); + for (let i = 0; i < 3; i++) { + const v1 = v1Parts[i] || 0; + const v2 = v2Parts[i] || 0; + if (v1 > v2) return 1; + if (v1 < v2) return -1; + } + return 0; +} +function hasStableTurboConfig() { + return compareVersions(getCurrentVersion(), '15.3.0') >= 0; +} +function isNextJs16OrHigher() { + return compareVersions(getCurrentVersion(), '16.0.0') >= 0; +} + +const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.cjs', document.baseURI).href))); +function withExtensions(localPath) { + return [`${localPath}.ts`, `${localPath}.tsx`, `${localPath}.js`, `${localPath}.jsx`]; +} +function normalizeTurbopackAliasPath(pathname) { + // Turbopack alias targets should use forward slashes; Windows backslashes can + // break resolution in dev (see `next-intl/config` alias path style). + return pathname.replace(/\\/g, '/'); +} + +/** + * Turbopack validates loader options by comparing them to their JSON round-trip + * (`isDeepStrictEqual(options, JSON.parse(JSON.stringify(options)))`). Since + * `JSON.stringify` drops keys with an `undefined` value, such a key would always + * fail that check, therefore they're removed here. + * https://github.com/amannn/next-intl/issues/2394 + */ +function pruneUndefined(value) { + if (Array.isArray(value)) { + return value.map(pruneUndefined); + } + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined).map(([key, entry]) => [key, pruneUndefined(entry)])); + } + return value; +} +function resolveI18nPath(providedPath, cwd) { + function resolvePath(pathname) { + const parts = []; + if (cwd) parts.push(cwd); + parts.push(pathname); + return path__default.default.resolve(...parts); + } + function pathExists(pathname) { + return fs__default.default.existsSync(resolvePath(pathname)); + } + if (providedPath) { + // We use the `isNextDevOrBuild` condition to avoid throwing errors + // if `next.config.ts` is read by a non-Next.js process. + // https://github.com/amannn/next-intl/discussions/2209#discussioncomment-15650927 + if (isDevelopmentOrNextBuild && !pathExists(providedPath)) { + throwError(`Could not find i18n config at ${providedPath}, please provide a valid path.`); + } + return providedPath; + } else { + for (const candidate of [...withExtensions('./i18n/request'), ...withExtensions('./src/i18n/request')]) { + if (pathExists(candidate)) { + return candidate; + } + } + if (isDevelopmentOrNextBuild) { + throwError(`Could not locate request configuration module.\n\nThis path is supported by default: ./(src/)i18n/request.{js,jsx,ts,tsx}\n\nAlternatively, you can specify a custom location in your Next.js config:\n\nconst withNextIntl = createNextIntlPlugin(\n './path/to/i18n/request.tsx'\n);`); + } + + // Default as fallback + if (pathExists('./src')) { + return './src/i18n/request.ts'; + } else { + return './i18n/request.ts'; + } + } +} +function getNextConfig(pluginConfig, nextConfig, extractorConfig) { + const useTurbo = process.env.TURBOPACK != null; + + // `experimental-analyze` doesn’t set the TURBOPACK env param. Since Next.js + // 16 doesn't print a warning when we configure both Turbo- and Webpack, just + // always configure Turbopack just in case. + const shouldConfigureTurbo = useTurbo || isNextJs16OrHigher(); + const nextIntlConfig = {}; + let messageLoadPaths = []; + if (pluginConfig.experimental?.messages) { + messageLoadPaths = normalizeMessagesCatalogPaths(pluginConfig.experimental.messages.path); + } + function getExtractMessagesLoaderConfig(config) { + return { + loader: 'next-intl/extractor/extractionLoader', + options: pruneUndefined(config) + }; + } + function getCatalogLoaderConfig() { + const experimental = pluginConfig.experimental; + const messages = experimental.messages; + // Normalization enforces a source locale before extraction runs. + const sourceLocale = messages.sourceLocale ?? (typeof experimental.extract === 'object' ? experimental.extract.sourceLocale : undefined); + return { + loader: 'next-intl/extractor/catalogLoader', + options: pruneUndefined({ + messages: { + format: messages.format, + precompile: messages.precompile, + sourceLocale + } + }) + }; + } + function getTurboRules() { + return nextConfig?.turbopack?.rules || + // @ts-expect-error -- For Next.js <16 + nextConfig?.experimental?.turbo?.rules || {}; + } + function addTurboRule(rules, glob, rule) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (rules[glob]) { + if (Array.isArray(rules[glob])) { + rules[glob].push(rule); + } else { + rules[glob] = [rules[glob], rule]; + } + } else { + rules[glob] = rule; + } + } + if (shouldConfigureTurbo) { + if (pluginConfig.requestConfig && path__default.default.isAbsolute(pluginConfig.requestConfig)) { + throwError("Turbopack support for next-intl currently does not support absolute paths, please provide a relative one (e.g. './src/i18n/config.ts').\n\nFound: " + pluginConfig.requestConfig); + } + + // Assign alias for `next-intl/config` + const resolveAlias = { + // Turbo aliases don't work with absolute + // paths (see error handling above) + 'next-intl/config': resolveI18nPath(pluginConfig.requestConfig) + }; + + // Add alias for precompiled message formatting + if (pluginConfig.experimental?.messages?.precompile) { + // Workaround for https://github.com/vercel/next.js/issues/88540 + let formatOnlyPath = path__default.default.relative(process.cwd(), require$1.resolve('use-intl/format-message/format-only')); + + // Turbopack seems to require this, otherwise `use-intl/format-message` is + // still bundled (despite the code correctly calling into `format-only`). + // Note that in this monorepo this is not necessary, because we'll end + // up with a path like `../…` — but for actual consumers this is required. + if (!formatOnlyPath.startsWith('.')) { + formatOnlyPath = `./${formatOnlyPath}`; + } + resolveAlias['use-intl/format-message'] = normalizeTurbopackAliasPath(formatOnlyPath); + } + + // Add loaders + let rules; + + // Add loader for extractor + if (pluginConfig.experimental?.extract) { + if (!isNextJs16OrHigher()) { + throwError('Message extraction requires Next.js 16 or higher.'); + } + rules ??= getTurboRules(); + addTurboRule(rules, `*.{${SourceFileFilter.EXTENSIONS.join(',')}}`, { + loaders: [getExtractMessagesLoaderConfig(extractorConfig)], + condition: { + // We don't filter for `path` here to allow transformation + // of `useExtracted` calls in external packages (e.g. monorepos) + content: /(useExtracted|getExtracted)/ + } + }); + } + + // Add loader for catalog + if (pluginConfig.experimental?.messages) { + if (!isNextJs16OrHigher()) { + throwError('Message catalog loading requires Next.js 16 or higher.'); + } + rules ??= getTurboRules(); + const extension = getFormatExtension(pluginConfig.experimental.messages.format); + addTurboRule(rules, `*${extension}`, { + loaders: [getCatalogLoaderConfig()], + condition: { + path: `{${messageLoadPaths.join(',')}}/**/*` + }, + as: '*.js' + }); + } + if (hasStableTurboConfig() && + // @ts-expect-error -- For Next.js <16 + !nextConfig?.experimental?.turbo) { + nextIntlConfig.turbopack = { + ...nextConfig?.turbopack, + ...(rules && { + rules + }), + resolveAlias: { + ...nextConfig?.turbopack?.resolveAlias, + ...resolveAlias + } + }; + } else { + nextIntlConfig.experimental = { + ...nextConfig?.experimental, + // @ts-expect-error -- For Next.js <16 + turbo: { + // @ts-expect-error -- For Next.js <16 + ...nextConfig?.experimental?.turbo, + ...(rules && { + rules + }), + resolveAlias: { + // @ts-expect-error -- For Next.js <16 + ...nextConfig?.experimental?.turbo?.resolveAlias, + ...resolveAlias + } + } + }; + } + } + if (!useTurbo) { + nextIntlConfig.webpack = function webpack(config, context) { + if (!config.resolve) config.resolve = {}; + if (!config.resolve.alias) config.resolve.alias = {}; + + // Assign alias for `next-intl/config` + // (Webpack requires absolute paths) + config.resolve.alias['next-intl/config'] = path__default.default.resolve(config.context, resolveI18nPath(pluginConfig.requestConfig, config.context)); + + // Add alias for precompiled message formatting + if (pluginConfig.experimental?.messages?.precompile) { + // Use require.resolve to get the actual file path, since + // bundlers don't properly resolve package subpath exports + // when used as alias targets + config.resolve.alias['use-intl/format-message'] = require$1.resolve('use-intl/format-message/format-only'); + } + + // Add loader for extractor + if (pluginConfig.experimental?.extract) { + if (!config.module) config.module = {}; + if (!config.module.rules) config.module.rules = []; + config.module.rules.push({ + test: new RegExp(`\\.(${SourceFileFilter.EXTENSIONS.join('|')})$`), + use: [getExtractMessagesLoaderConfig(extractorConfig)] + }); + } + + // Add loader for catalog + if (pluginConfig.experimental?.messages) { + if (!config.module) config.module = {}; + if (!config.module.rules) config.module.rules = []; + const extension = getFormatExtension(pluginConfig.experimental.messages.format); + config.module.rules.push({ + test: new RegExp(`${extension.replace(/\./g, '\\.')}$`), + include: messageLoadPaths.map(dirPath => path__default.default.resolve(config.context, dirPath)), + use: [getCatalogLoaderConfig()], + type: 'javascript/auto' + }); + } + if (typeof nextConfig?.webpack === 'function') { + return nextConfig.webpack(config, context); + } + return config; + }; + } + + // Forward config + const env = {}; + if (nextConfig?.trailingSlash) { + env._next_intl_trailing_slash = 'true'; + } + if (nextConfig?.basePath) { + env._next_intl_base_path = nextConfig.basePath; + } + // Note that `undefined` values are not supported by Turbopack + if (Object.keys(env).length > 0) { + nextIntlConfig.env = { + ...nextConfig?.env, + ...env + }; + } + return Object.assign({}, nextConfig, nextIntlConfig); +} + +function initPlugin(pluginConfig, nextConfig) { + if (nextConfig?.i18n != null) { + warn("An `i18n` property was found in your Next.js config. This likely causes conflicts and should therefore be removed if you use the App Router.\n\nIf you're in progress of migrating from the Pages Router, you can refer to this example: https://next-intl.dev/examples#app-router-migration\n"); + } + const skipWatchers = isNextTelemetryDetachedFlushProcess(); + const messagesPathOrPaths = pluginConfig.experimental?.createMessagesDeclaration; + if (messagesPathOrPaths && !skipWatchers) { + createMessagesDeclaration(typeof messagesPathOrPaths === 'string' ? [messagesPathOrPaths] : messagesPathOrPaths); + } + let extractorConfig; + const experimental = pluginConfig.experimental; + const extract = experimental?.extract; + if (extract) { + extractorConfig = normalizeExtractorConfig({ + extract, + messages: experimental.messages, + srcPath: experimental.srcPath + }); + } + if (!skipWatchers) { + initExtractionCompiler(extractorConfig); + } + return getNextConfig(pluginConfig, nextConfig, extractorConfig); +} +function createNextIntlPlugin(i18nPathOrConfig = {}) { + const config = typeof i18nPathOrConfig === 'string' ? { + requestConfig: i18nPathOrConfig + } : i18nPathOrConfig; + return function withNextIntl(nextConfig) { + return initPlugin(config, nextConfig); + }; +} + +/** + * Next runs `telemetry/detached-flush.js` in a detached process to flush telemetry + * (often when `next dev` exits). That loads dev `next.config` with inherited + * `NODE_ENV=development`, which would otherwise start orphan plugin watchers. + */ +function isNextTelemetryDetachedFlushProcess() { + const scriptPath = process.argv[1]; + if (!scriptPath) return false; + const normalized = scriptPath.replace(/\\/g, '/'); + return normalized.includes('/telemetry/detached-flush'); +} + +module.exports = createNextIntlPlugin; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/config.js b/e-commerce/node_modules/next-intl/dist/esm/development/config.js new file mode 100644 index 0000000000000000000000000000000000000000..6c21f227e73e56e8840cccf5a4b2c8e4042e0b22 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/config.js @@ -0,0 +1,5 @@ +function getConfig() { + throw new Error("Couldn't find next-intl config file. Please follow the instructions at https://next-intl.dev/docs/getting-started/app-router"); +} + +export { getConfig as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor.js new file mode 100644 index 0000000000000000000000000000000000000000..10c7a962bf2882c228ed65bdebd8302105cde673 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor.js @@ -0,0 +1,2 @@ +export { default as unstable_extractMessages } from './extractor/extractMessages.js'; +export { defineCodec } from './extractor/format/ExtractorCodec.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/ExtractionCompiler.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/ExtractionCompiler.js new file mode 100644 index 0000000000000000000000000000000000000000..0f85921ac2f03b34dc411c32f16b6fce08a1b4b2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/ExtractionCompiler.js @@ -0,0 +1,38 @@ +import CatalogManager from './catalog/CatalogManager.js'; +import MessageExtractor from './extractor/MessageExtractor.js'; + +class ExtractionCompiler { + constructor(config, opts = {}) { + const extractor = opts.extractor ?? new MessageExtractor(opts); + this.manager = new CatalogManager(config, { + ...opts, + extractor + }); + this[Symbol.dispose] = this[Symbol.dispose].bind(this); + this.installExitHandlers(); + } + async extractAll() { + // We can't rely on all files being compiled (e.g. due to persistent + // caching), so loading the messages initially is necessary. + await this.manager.loadMessages(); + await this.manager.save(); + } + [Symbol.dispose]() { + this.uninstallExitHandlers(); + this.manager[Symbol.dispose](); + } + installExitHandlers() { + const cleanup = this[Symbol.dispose]; + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + } + uninstallExitHandlers() { + const cleanup = this[Symbol.dispose]; + process.off('exit', cleanup); + process.off('SIGINT', cleanup); + process.off('SIGTERM', cleanup); + } +} + +export { ExtractionCompiler as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogLocales.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogLocales.js new file mode 100644 index 0000000000000000000000000000000000000000..9cf2db29c6c3d537fc83e42617c5a7ebe41272e4 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogLocales.js @@ -0,0 +1,84 @@ +import fs$1 from 'fs'; +import fs from 'fs/promises'; +import path from 'path'; + +class CatalogLocales { + onChangeCallbacks = new Set(); + constructor(params) { + this.messagesDir = params.messagesDir; + this.sourceLocale = params.sourceLocale; + this.extension = params.extension; + this.locales = params.locales; + } + async getTargetLocales() { + if (this.targetLocales) { + return this.targetLocales; + } + if (this.locales === 'infer') { + this.targetLocales = await this.readTargetLocales(); + } else { + this.targetLocales = this.locales.filter(locale => locale !== this.sourceLocale); + } + return this.targetLocales; + } + async readTargetLocales() { + try { + const files = await fs.readdir(this.messagesDir); + return files.filter(file => file.endsWith(this.extension)).map(file => path.basename(file, this.extension)).filter(locale => locale !== this.sourceLocale); + } catch { + return []; + } + } + subscribeLocalesChange(callback) { + this.onChangeCallbacks.add(callback); + if (this.locales === 'infer' && !this.watcher) { + void this.startWatcher(); + } + } + unsubscribeLocalesChange(callback) { + this.onChangeCallbacks.delete(callback); + if (this.onChangeCallbacks.size === 0) { + this.stopWatcher(); + } + } + async startWatcher() { + if (this.watcher) { + return; + } + await fs.mkdir(this.messagesDir, { + recursive: true + }); + this.watcher = fs$1.watch(this.messagesDir, { + persistent: false, + recursive: false + }, (event, filename) => { + const isCatalogFile = filename != null && filename.endsWith(this.extension) && !filename.includes(path.sep); + if (isCatalogFile) { + void this.onChange(); + } + }); + } + stopWatcher() { + if (this.watcher) { + this.watcher.close(); + this.watcher = undefined; + } + } + async onChange() { + const oldLocales = new Set(this.targetLocales || []); + this.targetLocales = await this.readTargetLocales(); + const newLocalesSet = new Set(this.targetLocales); + const added = this.targetLocales.filter(locale => !oldLocales.has(locale)); + const removed = Array.from(oldLocales).filter(locale => !newLocalesSet.has(locale)); + if (added.length > 0 || removed.length > 0) { + for (const callback of this.onChangeCallbacks) { + callback({ + added, + removed + }); + } + } + } +} + +export { CatalogLocales as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogManager.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogManager.js new file mode 100644 index 0000000000000000000000000000000000000000..0b5266501b4bfc1d4b095e418a97f4f8c3426e5f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogManager.js @@ -0,0 +1,422 @@ +import fs from 'fs/promises'; +import path from 'path'; +import { resolveCodec, getFormatExtension } from '../format/index.js'; +import SourceFileScanner from '../source/SourceFileScanner.js'; +import SourceFileWatcher from '../source/SourceFileWatcher.js'; +import { getDefaultProjectRoot, localeCompare, compareReferences } from '../utils.js'; +import CatalogLocales from './CatalogLocales.js'; +import CatalogPersister from './CatalogPersister.js'; +import SaveScheduler from './SaveScheduler.js'; + +class CatalogManager { + /** + * Extraction-derived fields aggregated into `ExtractorMessage`. + * Source code is the source of truth for these fields, only ancillary + * codec fields may merge from disk (e.g. flags). + */ + static extractorOwnedAggregatorKeys = new Set(['description', 'id', 'message', 'references']); + /** + * Source of truth for statically extracted source messages, + * grouped by file and message ID. + */ + sourceMessagesByFile = new Map(); + + /** + * Reverse index for rebuilding aggregated messages without scanning all files. + * Contains the same `SourceExtractedMessage` arrays as `sourceMessagesByFile` and is + * kept in sync with it. + */ + sourceMessagesById = new Map(); + + /** + * Fast lookup for messages by ID, aggregated across all files. This combines + * metadata from `sourceMessagesById`, e.g. references and descriptions. + */ + messagesById = new Map(); + + /** + * This potentially also includes outdated ones that were initially available, + * but are not used anymore. This allows to restore them if they are used again. + **/ + translationsByTargetLocale = new Map(); + lastWriteByLocale = new Map(); + + // Cached instances + + // Resolves when all catalogs are loaded + + // Resolves when the initial project scan and processing is complete + + constructor(config, opts) { + this.config = config; + this.saveScheduler = new SaveScheduler(opts.saveDebounceMs ?? 50); + this.projectRoot = opts.projectRoot ?? getDefaultProjectRoot(); + this.isDevelopment = opts.isDevelopment ?? false; + this.extractor = opts.extractor; + if (this.isDevelopment) { + // We kick this off as early as possible, so we get notified about changes + // that happen during the initial project scan (while awaiting it to + // complete though) + this.sourceWatcher = new SourceFileWatcher(this.getSrcPaths(), this.handleFileEvents.bind(this)); + void this.sourceWatcher.start(); + } + } + async getCodec() { + if (!this.codec) { + this.codec = await resolveCodec(this.config.messages.format, this.projectRoot); + } + return this.codec; + } + async getPersister() { + if (this.persister) { + return this.persister; + } else { + this.persister = new CatalogPersister({ + messagesPath: this.config.extract.path, + codec: await this.getCodec(), + extension: getFormatExtension(this.config.messages.format), + sourceLocale: this.config.extract.sourceLocale + }); + return this.persister; + } + } + getCatalogLocales() { + if (this.catalogLocales) { + return this.catalogLocales; + } else { + const messagesDir = path.join(this.projectRoot, this.config.extract.path); + this.catalogLocales = new CatalogLocales({ + messagesDir, + extension: getFormatExtension(this.config.messages.format), + locales: this.config.extract.locales, + sourceLocale: this.config.extract.sourceLocale + }); + return this.catalogLocales; + } + } + async getTargetLocales() { + return this.getCatalogLocales().getTargetLocales(); + } + getSrcPaths() { + return (Array.isArray(this.config.extract.srcPath) ? this.config.extract.srcPath : [this.config.extract.srcPath]).map(srcPath => path.join(this.projectRoot, srcPath)); + } + async loadMessages() { + const sourceDiskMessages = await this.loadSourceMessages(); + this.loadCatalogsPromise = this.loadTargetMessages(); + await this.loadCatalogsPromise; + this.scanCompletePromise = (async () => { + const sourceFiles = Array.from(await SourceFileScanner.getSourceFiles(this.getSrcPaths())) + // Stable file order keeps catalog ties independent of processing timing + .toSorted(localeCompare); + const extractedFiles = await Promise.all(sourceFiles.map(async filePath => ({ + filePath, + messages: await this.extractFile(filePath) + }))); + for (const { + filePath, + messages + } of extractedFiles) { + if (messages) { + this.applyFileMessages(filePath, messages); + } + } + this.mergeSourceDiskMetadata(sourceDiskMessages); + })(); + await this.scanCompletePromise; + if (this.isDevelopment) { + const catalogLocales = this.getCatalogLocales(); + catalogLocales.subscribeLocalesChange(this.onLocalesChange); + } + } + async loadSourceMessages() { + // Load source catalog to hydrate metadata (e.g. flags) later without + // treating catalog entries as source of truth. + const diskMessages = await this.loadLocaleMessages(this.config.extract.sourceLocale); + const byId = new Map(); + for (const diskMessage of diskMessages) { + byId.set(diskMessage.id, diskMessage); + } + return byId; + } + async loadLocaleMessages(locale) { + const persister = await this.getPersister(); + const messages = await persister.read(locale); + const fileTime = await persister.getLastModified(locale); + this.lastWriteByLocale.set(locale, fileTime); + return messages; + } + async loadTargetMessages() { + const targetLocales = await this.getTargetLocales(); + await Promise.all(targetLocales.map(locale => this.reloadLocaleCatalog(locale))); + } + async reloadLocaleCatalog(locale) { + const diskMessages = await this.loadLocaleMessages(locale); + if (locale === this.config.extract.sourceLocale) { + // For source: Merge additional properties like flags + for (const diskMessage of diskMessages) { + const prev = this.messagesById.get(diskMessage.id); + if (prev) { + for (const key of Object.keys(diskMessage)) { + if (!CatalogManager.extractorOwnedAggregatorKeys.has(key)) { + // For unknown properties (like flags), disk wins + prev[key] = diskMessage[key]; + } + } + } + } + } else { + // For target: disk wins completely, BUT preserve existing translations + // if we read empty (likely a write in progress by an external tool + // that causes the file to temporarily be empty) + const existingTranslations = this.translationsByTargetLocale.get(locale); + const hasExistingTranslations = existingTranslations && existingTranslations.size > 0; + if (diskMessages.length > 0) { + // We got content from disk, replace with it + const translations = new Map(); + for (const message of diskMessages) { + translations.set(message.id, message); + } + this.translationsByTargetLocale.set(locale, translations); + } else if (hasExistingTranslations) ; else { + // We read empty and have no existing translations + const translations = new Map(); + this.translationsByTargetLocale.set(locale, translations); + } + } + } + mergeSourceDiskMetadata(diskMessages) { + for (const [id, diskMessage] of diskMessages) { + const existing = this.messagesById.get(id); + if (!existing) continue; + + // Fill unknown metadata from disk without replacing extraction-owned fields. + for (const key of Object.keys(diskMessage)) { + if (!CatalogManager.extractorOwnedAggregatorKeys.has(key) && existing[key] == null) { + existing[key] = diskMessage[key]; + } + } + } + } + async processFile(absoluteFilePath) { + const messages = await this.extractFile(absoluteFilePath); + + // `undefined` only when `extractFile()` throws. An empty array is success + // and must still run `applyFileMessages` to clear stale ids for this file. + if (!messages) return false; + return this.applyFileMessages(absoluteFilePath, messages); + } + async extractFile(absoluteFilePath) { + let messages = []; + try { + const content = await fs.readFile(absoluteFilePath, 'utf8'); + let extraction; + try { + extraction = await this.extractor.extract(absoluteFilePath, content); + } catch { + return undefined; + } + messages = extraction.messages; + } catch (err) { + if (err.code !== 'ENOENT') { + throw err; + } + // ENOENT -> treat as no messages + } + return messages; + } + applyFileMessages(absoluteFilePath, messages) { + const prevFileMessages = this.sourceMessagesByFile.get(absoluteFilePath); + const nextFileMessages = this.groupSourceMessagesById(messages); + const affectedIds = new Set([...(prevFileMessages?.keys() ?? []), ...nextFileMessages.keys()]); + if (nextFileMessages.size > 0) { + this.sourceMessagesByFile.set(absoluteFilePath, nextFileMessages); + } else { + this.sourceMessagesByFile.delete(absoluteFilePath); + } + + // Clear this file's contribution from the reverse index, then re-insert + // fresh rows and rebuild aggregates (messagesById) per touched id. + for (const id of affectedIds) { + const sourceMessagesForId = this.sourceMessagesById.get(id); + if (sourceMessagesForId) { + sourceMessagesForId.delete(absoluteFilePath); + // No files left for this id: drop the reverse-index entry. + if (sourceMessagesForId.size === 0) { + this.sourceMessagesById.delete(id); + } + } + const nextSourceMessagesForId = nextFileMessages.get(id); + if (nextSourceMessagesForId) { + let sourceMessagesByFile = this.sourceMessagesById.get(id); + if (!sourceMessagesByFile) { + sourceMessagesByFile = new Map(); + this.sourceMessagesById.set(id, sourceMessagesByFile); + } + sourceMessagesByFile.set(absoluteFilePath, nextSourceMessagesForId); + } + this.rebuildMessageById(id); + } + const changed = this.haveMessagesChangedForFile(prevFileMessages, nextFileMessages); + return changed; + } + groupSourceMessagesById(messages) { + const result = new Map(); + for (const message of messages) { + const messagesById = result.get(message.id); + if (messagesById) { + messagesById.push(message); + } else { + result.set(message.id, [message]); + } + } + return result; + } + rebuildMessageById(id) { + const sourceMessages = Array.from(this.sourceMessagesById.get(id)?.values() ?? []).flat(); + if (sourceMessages.length === 0) { + this.messagesById.delete(id); + return; + } + const previousMessage = this.messagesById.get(id); + const aggregate = { + description: this.mergeDescriptions(sourceMessages), + id, + message: sourceMessages[0].message, + references: sourceMessages.map(message => message.reference).sort(compareReferences) + }; + if (previousMessage) { + for (const key of Object.keys(previousMessage)) { + // Preserve extra fields (e.g. from disk/codec) across rebuilds; the + // four core fields above are always recomputed from source messages. + if (!CatalogManager.extractorOwnedAggregatorKeys.has(key) && aggregate[key] == null) { + aggregate[key] = previousMessage[key]; + } + } + } + this.messagesById.set(id, aggregate); + } + mergeDescriptions(messages) { + const sortedByReference = messages.toSorted((a, b) => compareReferences(a.reference, b.reference)); + const merged = []; + for (const message of sortedByReference) { + const { + description + } = message; + if (description != null && !merged.includes(description)) { + merged.push(description); + } + } + return merged; + } + haveMessagesChangedForFile(beforeMessages, afterMessages) { + // If one exists and the other doesn't, there's a change + if (!beforeMessages) { + return afterMessages.size > 0; + } + + // Different sizes means changes + if (beforeMessages.size !== afterMessages.size) { + return true; + } + + // Check differences in beforeMessages vs afterMessages + for (const [id, prevSourceMessages] of beforeMessages) { + const nextSourceMessages = afterMessages.get(id); + if (!nextSourceMessages) { + return true; + } + if (!this.areSourceMessageArraysEqual(prevSourceMessages, nextSourceMessages)) { + return true; // Early exit on first difference + } + } + return false; + } + areSourceMessageArraysEqual(messages1, messages2) { + return messages1.length === messages2.length && messages1.every((message, index) => this.areSourceMessagesEqual(message, messages2[index])); + } + areSourceMessagesEqual(msg1, msg2) { + return msg1.id === msg2.id && msg1.message === msg2.message && msg1.description === msg2.description && msg1.reference.path === msg2.reference.path && msg1.reference.line === msg2.reference.line && msg1.reference.column === msg2.reference.column; + } + async save() { + return this.saveScheduler.schedule(() => this.saveImpl()); + } + async saveImpl() { + await this.saveLocale(this.config.extract.sourceLocale); + const targetLocales = await this.getTargetLocales(); + await Promise.all(targetLocales.map(locale => this.saveLocale(locale))); + } + async saveLocale(locale) { + await this.loadCatalogsPromise; + const messages = Array.from(this.messagesById.values()); + const persister = await this.getPersister(); + const isSourceLocale = locale === this.config.extract.sourceLocale; + + // Check if file was modified externally (poll-at-save is cheaper than + // watchers here since stat() is fast and avoids continuous overhead) + const lastWriteTime = this.lastWriteByLocale.get(locale); + const currentFileTime = await persister.getLastModified(locale); + if (currentFileTime && lastWriteTime && currentFileTime > lastWriteTime) { + await this.reloadLocaleCatalog(locale); + } + const localeMessages = isSourceLocale ? this.messagesById : this.translationsByTargetLocale.get(locale); + const messagesToPersist = messages.map(message => { + const localeMessage = localeMessages?.get(message.id); + return { + ...localeMessage, + id: message.id, + description: message.description, + references: message.references, + message: isSourceLocale ? message.message : localeMessage?.message ?? '' + }; + }); + await persister.write(messagesToPersist, { + locale, + sourceMessagesById: this.messagesById + }); + + // Update timestamps + const newTime = await persister.getLastModified(locale); + this.lastWriteByLocale.set(locale, newTime); + } + onLocalesChange = async params => { + // Chain to existing promise + this.loadCatalogsPromise = Promise.all([this.loadCatalogsPromise, ...params.added.map(locale => this.reloadLocaleCatalog(locale))]); + for (const locale of params.added) { + await this.saveLocale(locale); + } + for (const locale of params.removed) { + this.translationsByTargetLocale.delete(locale); + this.lastWriteByLocale.delete(locale); + } + }; + async handleFileEvents(events) { + if (this.loadCatalogsPromise) { + await this.loadCatalogsPromise; + } + + // Wait for initial scan to complete to avoid race conditions + if (this.scanCompletePromise) { + await this.scanCompletePromise; + } + let changed = false; + const expandedEvents = await this.sourceWatcher.expandDirectoryDeleteEvents(events, Array.from(this.sourceMessagesByFile.keys())); + // Stable file order keeps catalog ties independent of event timing. + for (const event of expandedEvents.toSorted((a, b) => localeCompare(a.path, b.path))) { + const hasChanged = await this.processFile(event.path); + changed ||= hasChanged; + } + if (changed) { + await this.save(); + } + } + [Symbol.dispose]() { + this.sourceWatcher?.stop(); + this.sourceWatcher = undefined; + this.saveScheduler[Symbol.dispose](); + if (this.catalogLocales && this.isDevelopment) { + this.catalogLocales.unsubscribeLocalesChange(this.onLocalesChange); + } + } +} + +export { CatalogManager as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogPersister.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogPersister.js new file mode 100644 index 0000000000000000000000000000000000000000..1c082bb407a7285582c819128e9b433ba0d0d11d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/CatalogPersister.js @@ -0,0 +1,82 @@ +import fs from 'fs/promises'; +import path from 'path'; +import { warnAboutMissingReferences } from '../utils.js'; + +class CatalogPersister { + constructor(params) { + this.messagesPath = params.messagesPath; + this.codec = params.codec; + this.extension = params.extension; + this.sourceLocale = params.sourceLocale; + } + getFileName(locale) { + return locale + this.extension; + } + getFilePath(locale) { + return path.join(this.messagesPath, this.getFileName(locale)); + } + async read(locale) { + const filePath = this.getFilePath(locale); + let content; + try { + content = await fs.readFile(filePath, 'utf8'); + } catch (error) { + if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') { + return []; + } + throw new Error(`Error while reading ${this.getFileName(locale)}:\n> ${error}`, { + cause: error + }); + } + try { + const messages = this.codec.decode(content, { + locale, + sourceLocale: this.sourceLocale + }); + assertNoArrayMessages(messages); + return messages; + } catch (error) { + throw new Error(`Error while decoding ${this.getFileName(locale)}:\n> ${error}`, { + cause: error + }); + } + } + async write(messages, context) { + const filePath = this.getFilePath(context.locale); + warnAboutMissingReferences(messages); + const content = this.codec.encode(messages, context); + try { + const outputDir = path.dirname(filePath); + await fs.mkdir(outputDir, { + recursive: true + }); + await fs.writeFile(filePath, content); + } catch (error) { + console.error(`❌ Failed to write catalog: ${error}`); + } + } + async getLastModified(locale) { + const filePath = this.getFilePath(locale); + try { + const stats = await fs.stat(filePath); + return stats.mtime; + } catch { + return undefined; + } + } +} + +// The codecs read arrays fine (numeric path segments), but the runtime only +// supports strings — enforced here where the runtime's rules apply. +function assertNoArrayMessages(messages) { + for (const message of messages) { + const segments = message.segments; + if (!Array.isArray(segments)) continue; + const firstIndex = segments.findIndex(segment => typeof segment === 'number'); + if (firstIndex === -1) continue; + const arrayPath = segments.slice(0, firstIndex).join('.'); + throw new Error(`Message at \`${arrayPath}\` resolved to an array, but only strings are supported. See https://next-intl.dev/docs/usage/translations#arrays-of-messages`); + } +} + +export { CatalogPersister as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/SaveScheduler.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/SaveScheduler.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2be16022edbe1f55f7b2040e7ec4d7bc517989 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalog/SaveScheduler.js @@ -0,0 +1,85 @@ +/** + * De-duplicates excessive save invocations, + * while keeping a single one instant. + */ +class SaveScheduler { + isSaving = false; + pendingResolvers = []; + constructor(delayMs = 50) { + this.delayMs = delayMs; + } + async schedule(saveTask) { + return new Promise((resolve, reject) => { + this.pendingResolvers.push({ + resolve, + reject + }); + this.nextSaveTask = saveTask; + if (!this.isSaving && !this.saveTimeout) { + // Not currently saving and no scheduled save, save immediately + this.executeSave(); + } else if (this.saveTimeout) { + // A save is already scheduled, reschedule to debounce + this.scheduleSave(); + } + // If isSaving is true and no timeout is scheduled, the current save + // will check for pending resolvers when it completes and schedule + // another save if needed (see finally block in executeSave) + }); + } + scheduleSave() { + if (this.saveTimeout) { + clearTimeout(this.saveTimeout); + } + this.saveTimeout = setTimeout(() => { + this.saveTimeout = undefined; + this.executeSave(); + }, this.delayMs); + } + async executeSave() { + if (this.isSaving) { + return; + } + const saveTask = this.nextSaveTask; + if (!saveTask) { + return; + } + + // Capture current pending resolvers for this save + const resolversForThisSave = this.pendingResolvers; + this.pendingResolvers = []; + this.nextSaveTask = undefined; + this.isSaving = true; + try { + const result = await saveTask(); + + // Resolve only the promises that were pending when this save started + resolversForThisSave.forEach(({ + resolve + }) => resolve(result)); + } catch (error) { + // Reject only the promises that were pending when this save started + resolversForThisSave.forEach(({ + reject + }) => reject(error)); + } finally { + this.isSaving = false; + + // If new saves were requested during this save, schedule another + if (this.pendingResolvers.length > 0) { + this.scheduleSave(); + } + } + } + [Symbol.dispose]() { + if (this.saveTimeout) { + clearTimeout(this.saveTimeout); + this.saveTimeout = undefined; + } + this.pendingResolvers = []; + this.nextSaveTask = undefined; + this.isSaving = false; + } +} + +export { SaveScheduler as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalogLoader.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalogLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..dba271de3347faff605719ec2d0fcdc73eb318c7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/catalogLoader.js @@ -0,0 +1,118 @@ +import path from 'path'; +import compile from 'icu-minify/compile'; +import { getFormatExtension, resolveCodec } from './format/index.js'; +import { setNestedProperty } from './utils.js'; + +// The module scope is safe for some caching, but Next.js can +// create multiple loader instances so don't expect a singleton. +let cachedCodec = null; +let hasWarnedAboutToJSONString = false; +const messageCacheByCatalog = new Map(); +function getMessageCache(catalogId) { + let cache = messageCacheByCatalog.get(catalogId); + if (!cache) { + cache = new Map(); + messageCacheByCatalog.set(catalogId, cache); + } + return cache; +} +async function getCodec(options, projectRoot) { + if (!cachedCodec) { + cachedCodec = await resolveCodec(options.messages.format, projectRoot); + } + return cachedCodec; +} + +/** + * Parses and optimizes catalog files. + * + * Note that if we use a dynamic import like `import(`${locale}.json`)`, then + * the loader will optimistically run for all candidates in this folder (both + * during dev as well as at build time). + */ +function catalogLoader(source) { + const options = this.getOptions(); + const callback = this.async(); + const extension = getFormatExtension(options.messages.format); + getCodec(options, this.rootContext).then(codec => { + warnIfToJSONStringProvided(codec); + const locale = path.basename(this.resourcePath, extension); + const decoded = codec.decode(source, { + locale, + sourceLocale: options.messages.sourceLocale + }); + let messages; + if (options.messages.precompile) { + const cache = getMessageCache(this.resourcePath); + messages = precompileMessages(decoded, cache); + } else { + messages = buildMessages(decoded); + } + + // https://v8.dev/blog/cost-of-javascript-2019#json + const result = `export default JSON.parse(${JSON.stringify(JSON.stringify(messages))});`; + callback(null, result); + }).catch(callback); +} +function warnIfToJSONStringProvided(codec) { + if (hasWarnedAboutToJSONString || !codec.toJSONString) return; + hasWarnedAboutToJSONString = true; + console.warn('`toJSONString` is deprecated and no longer needed, please remove it.'); +} + +/** + * Builds a nested messages object from decoded messages, mirroring the shape + * produced by `precompileMessages` but keeping the raw message strings. + */ +function buildMessages(messages) { + const result = Object.create(null); + for (const message of messages) { + assertStringMessage(message); + setNestedProperty(result, message.id, message.message); + } + return result; +} +function assertStringMessage(message) { + const messageValue = message.message; + if (Array.isArray(messageValue)) { + throw new Error(`Message at \`${message.id}\` resolved to an array, but only strings are supported. See https://next-intl.dev/docs/usage/translations#arrays-of-messages`); + } + if (typeof messageValue === 'object') { + throw new Error(`Message at \`${message.id}\` resolved to \`${typeof messageValue}\`, but only strings are supported. Use a \`.\` to retrieve nested messages. See https://next-intl.dev/docs/usage/translations#structuring-messages`); + } +} + +/** + * Recursively precompiles all ICU message strings in a messages object + * using icu-minify/compile for smaller runtime bundles. + */ +function precompileMessages(messages, cache) { + const result = Object.create(null); + const cacheKeysToEvict = new Set(cache.keys()); + for (const message of messages) { + cacheKeysToEvict.delete(message.id); + assertStringMessage(message); + const messageValue = message.message; + const cachedEntry = cache.get(message.id); + const hasCacheMatch = cachedEntry?.messageValue === messageValue; + let compiledMessage; + if (hasCacheMatch) { + compiledMessage = cachedEntry.compiledMessage; + } else { + compiledMessage = compile(messageValue); + cache.set(message.id, { + compiledMessage, + messageValue + }); + } + setNestedProperty(result, message.id, compiledMessage); + } + + // Evict unused cache entries + for (const cachedId of cacheKeysToEvict) { + cache.delete(cachedId); + } + return result; +} + +export { catalogLoader as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractMessages.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractMessages.js new file mode 100644 index 0000000000000000000000000000000000000000..58e8ba27eac2770e93e7fea047932390da8744d2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractMessages.js @@ -0,0 +1,22 @@ +import { warn } from '../plugin/utils.js'; +import ExtractionCompiler from './ExtractionCompiler.js'; +import MessageExtractor from './extractor/MessageExtractor.js'; +import normalizeExtractorConfig from './normalizeExtractorConfig.js'; +import { hasLocalesToExtract, getDefaultProjectRoot } from './utils.js'; + +async function extractMessages(params) { + const config = normalizeExtractorConfig(params); + if (!hasLocalesToExtract(config)) { + warn('`messages.locales` is empty, so no messages were updated.'); + return; + } + const compiler = new ExtractionCompiler(config, { + extractor: new MessageExtractor({ + isDevelopment: false, + projectRoot: getDefaultProjectRoot() + }) + }); + await compiler.extractAll(); +} + +export { extractMessages as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractionLoader.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractionLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..95f5ad102d3a0f5829e3c309b4b45f51dae4b74d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractionLoader.js @@ -0,0 +1,28 @@ +import MessageExtractor from './extractor/MessageExtractor.js'; + +// Module-level extractor instance for transformation caching. +// Note: Next.js/Turbopack may create multiple loader instances, but each +// only handles file transformation. The ExtractionCompiler (which manages +// catalogs) is initialized separately in createNextIntlPlugin. +let extractor; +function extractionLoader(source) { + const callback = this.async(); + const projectRoot = this.rootContext; + + // Avoid rollup's `replace` plugin to compile this away + const isDevelopment = process.env['NODE_ENV'.trim()] === 'development'; + if (!extractor) { + extractor = new MessageExtractor({ + isDevelopment, + projectRoot, + sourceMap: this.sourceMap + }); + } + extractor.extract(this.resourcePath, source).then(result => { + // Webpack loaders conventionally pass source maps as objects (e.g. + // `next-swc-loader` calls `JSON.stringify` on its input source map) + callback(null, result.code, result.map ? JSON.parse(result.map) : undefined); + }).catch(callback); +} + +export { extractionLoader as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractor/LRUCache.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractor/LRUCache.js new file mode 100644 index 0000000000000000000000000000000000000000..eedc754d8e3c0d4c23adba137ff8ea8e550bee5c --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractor/LRUCache.js @@ -0,0 +1,30 @@ +class LRUCache { + constructor(maxSize) { + this.maxSize = maxSize; + this.cache = new Map(); + } + set(key, value) { + const isNewKey = !this.cache.has(key); + if (isNewKey && this.cache.size >= this.maxSize) { + const lruKey = this.cache.keys().next().value; + if (lruKey !== undefined) { + this.cache.delete(lruKey); + } + } + this.cache.set(key, { + key, + value + }); + } + get(key) { + const item = this.cache.get(key); + if (item) { + this.cache.delete(key); + this.cache.set(key, item); + return item.value; + } + return undefined; + } +} + +export { LRUCache as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractor/MessageExtractor.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractor/MessageExtractor.js new file mode 100644 index 0000000000000000000000000000000000000000..2e3152752eb14045b218ba80d14d073416d986c5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/extractor/MessageExtractor.js @@ -0,0 +1,75 @@ +import { createRequire } from 'module'; +import path from 'path'; +import { transform } from '@swc/core'; +import { getDefaultProjectRoot, normalizePathToPosix } from '../utils.js'; +import LRUCache from './LRUCache.js'; + +const require$1 = createRequire(import.meta.url); +class MessageExtractor { + compileCache = new LRUCache(750); + constructor(opts) { + this.isDevelopment = opts.isDevelopment ?? false; + this.projectRoot = opts.projectRoot ?? getDefaultProjectRoot(); + this.sourceMap = opts.sourceMap ?? false; + } + async extract(absoluteFilePath, source) { + const cacheKey = [source, absoluteFilePath].join('!'); + const cached = this.compileCache.get(cacheKey); + if (cached) return cached; + + // Shortcut parsing if hook is not used. The Turbopack integration already + // pre-filters this, but for webpack this feature doesn't exist, so we need + // to do it here. + if (!source.includes('useExtracted') && !source.includes('getExtracted')) { + return { + messages: [], + code: source + }; + } + const filePath = normalizePathToPosix(path.relative(this.projectRoot, absoluteFilePath)); + const result = await transform(source, { + jsc: { + target: 'esnext', + parser: { + syntax: 'typescript', + tsx: true, + decorators: true + }, + experimental: { + cacheRoot: 'node_modules/.cache/swc', + disableBuiltinTransformsForInternalTesting: true, + disableAllLints: true, + plugins: [[require$1.resolve('next-intl-swc-plugin-extractor'), { + isDevelopment: this.isDevelopment, + filePath + }]] + } + }, + sourceMaps: this.sourceMap, + // Is converted into a relative path by Next.js when + // the final source map is generated + sourceFileName: absoluteFilePath, + filename: filePath + }); + + // TODO: Improve the typing of @swc/core + const output = result.output; + // The plugin emits a tagged union of extracted messages and + // `useTranslations` usages; this extractor only consumes the former. + const messages = JSON.parse(JSON.parse(output).results).filter(item => item.type === 'extracted').map(item => ({ + id: item.id, + message: item.message, + description: item.description, + reference: item.reference + })); + const extractionResult = { + code: result.code, + map: result.map, + messages + }; + this.compileCache.set(cacheKey, extractionResult); + return extractionResult; + } +} + +export { MessageExtractor as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/ExtractorCodec.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/ExtractorCodec.js new file mode 100644 index 0000000000000000000000000000000000000000..a5443c493b36a71e11133d1d51d10ebff4595300 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/ExtractorCodec.js @@ -0,0 +1,8 @@ +// Derived from `@eloqnt/config`, so next-intl and eloqnt pass identical +// options to codecs. + +function defineCodec(factory) { + return factory; +} + +export { defineCodec }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/codecs/BuiltInPoCodec.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/codecs/BuiltInPoCodec.js new file mode 100644 index 0000000000000000000000000000000000000000..34f3fed9b0bc55419f7527be0d5ca54312e61cc2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/codecs/BuiltInPoCodec.js @@ -0,0 +1,22 @@ +import createPoCodec from '@eloqnt/format-po'; +import { defineCodec } from '../ExtractorCodec.js'; + +// `@eloqnt/format-po`, guarded so catalogs in the previous key-based layout +// fail loudly. Custom codecs referencing the package directly opt out. +var BuiltInPoCodec = defineCodec(() => { + const codec = createPoCodec(); + function assertMigrated(content) { + if (content.includes('X-Crowdin-SourceKey: msgstr')) { + throw new Error('This catalog uses the previous PO layout of next-intl, which stored message keys in `msgid`. The PO format now follows the gettext convention: the source text in `msgid` and the message key in `msgctxt`. Please migrate your catalogs, or use a custom codec to keep the previous layout: https://github.com/amannn/next-intl/pull/2393'); + } + } + return { + ...codec, + decode(content, context) { + assertMigrated(content); + return codec.decode(content, context); + } + }; +}); + +export { BuiltInPoCodec as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/index.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d653f9c253eda7c7b41a4e4c3e395db5fe3e993d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/format/index.js @@ -0,0 +1,59 @@ +import { createRequire } from 'module'; +import path from 'path'; +import { pathToFileURL } from 'url'; +import { throwError } from '../../plugin/utils.js'; + +const formats = { + json: { + codec: () => import('@eloqnt/format-json'), + extension: '.json' + }, + po: { + codec: () => import('./codecs/BuiltInPoCodec.js'), + extension: '.po' + } +}; +function isBuiltInFormat(format) { + return typeof format === 'string' && format in formats; +} +function getFormatExtension(format) { + if (isBuiltInFormat(format)) { + return formats[format].extension; + } else { + return format.extension; + } +} +async function resolveCodec(format, projectRoot) { + if (isBuiltInFormat(format)) { + const factory = (await formats[format].codec()).default; + return factory(); + } else { + // A codec that starts with `.` or a filesystem root is a file path; + // everything else reads as a package specifier, mirroring how imports + // distinguish the two. Packages resolve from the project's dependencies. + const isPath = format.codec.startsWith('.') || path.isAbsolute(format.codec); + let resolvedPath; + if (isPath) { + resolvedPath = path.resolve(projectRoot, format.codec); + } else { + try { + resolvedPath = createRequire(path.join(projectRoot, 'noop.js')).resolve(format.codec); + } catch (error) { + throwError(`Could not resolve the codec package "${format.codec}". Is it installed?\n${error}`); + } + } + let module; + try { + module = await import(pathToFileURL(resolvedPath).href); + } catch (error) { + throwError(`Could not load codec from "${resolvedPath}".\n${error}`); + } + const factory = module.default; + if (!factory || typeof factory !== 'function') { + throwError(`Codec at "${resolvedPath}" must have a default export returned from \`defineCodec\`.`); + } + return factory(); + } +} + +export { formats as default, getFormatExtension, resolveCodec }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/normalizeExtractorConfig.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/normalizeExtractorConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..2023decbfc2272bc07b04ce1a6b575654480a152 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/normalizeExtractorConfig.js @@ -0,0 +1,70 @@ +import { throwError, warn } from '../plugin/utils.js'; + +function stripTrailingSlash(dirPath) { + if (dirPath.endsWith('/')) { + return dirPath.slice(0, -1); + } else { + return dirPath; + } +} +function normalizeMessagesCatalogPaths(messagesPath) { + const rawPaths = Array.isArray(messagesPath) ? messagesPath : [messagesPath]; + return rawPaths.map(dirPath => stripTrailingSlash(String(dirPath).trim())).filter(dirPath => dirPath.length > 0); +} +function normalizeExtractorConfig(input) { + if (input.messages == null) { + throwError('`messages` is required when extracting messages.'); + } + const extract = input.extract; + let extractPath; + let sourceLocale; + if (extract !== undefined && extract !== true) { + if (extract.sourceLocale) { + warn('`extract.sourceLocale` is deprecated in favor of `messages.sourceLocale`.'); + sourceLocale = extract.sourceLocale; + } + if (extract.path) { + extractPath = stripTrailingSlash(extract.path); + } + } + const locales = input.messages.locales; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!locales) { + throwError('`messages.locales` is required when extracting messages.'); + } + if (input.messages.sourceLocale) { + sourceLocale = input.messages.sourceLocale; + } + if (!sourceLocale) { + throwError('`messages.sourceLocale` is required when extracting messages.'); + } + const srcPath = input.srcPath; + if (srcPath == null) { + throwError('`srcPath` is required when extracting messages.'); + } + const pathIsArray = Array.isArray(input.messages.path); + const messagesPath = normalizeMessagesCatalogPaths(input.messages.path); + if (messagesPath.length === 0) { + throwError('`messages.path` must not be empty.'); + } + if (extractPath == null) { + if (pathIsArray) { + throwError('When `messages.path` is an array, `extract.path` is required to select the writable catalog directory.'); + } + extractPath = messagesPath[0]; + } + return { + extract: { + locales, + path: extractPath, + sourceLocale, + srcPath + }, + messages: { + format: input.messages.format, + path: messagesPath + } + }; +} + +export { normalizeExtractorConfig as default, normalizeMessagesCatalogPaths }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileFilter.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileFilter.js new file mode 100644 index 0000000000000000000000000000000000000000..767d214e37b7507417ae896eba1790633f9e334f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileFilter.js @@ -0,0 +1,29 @@ +import path from 'path'; + +class SourceFileFilter { + static EXTENSIONS = ['ts', 'tsx', 'js', 'jsx']; + + // Will not be entered, except if explicitly asked for + // TODO: At some point we should infer these from .gitignore + static IGNORED_DIRECTORIES = ['node_modules', '.next', '.git']; + static isSourceFile(filePath) { + const ext = path.extname(filePath); + return SourceFileFilter.EXTENSIONS.map(cur => '.' + cur).includes(ext); + } + static shouldEnterDirectory(dirPath, srcPaths) { + const dirName = path.basename(dirPath); + if (SourceFileFilter.IGNORED_DIRECTORIES.includes(dirName)) { + return SourceFileFilter.isIgnoredDirectoryExplicitlyIncluded(dirPath, srcPaths); + } + return true; + } + static isIgnoredDirectoryExplicitlyIncluded(ignoredDirPath, srcPaths) { + return srcPaths.some(srcPath => SourceFileFilter.isWithinPath(srcPath, ignoredDirPath)); + } + static isWithinPath(targetPath, basePath) { + const relativePath = path.relative(basePath, targetPath); + return relativePath === '' || !relativePath.startsWith('..'); + } +} + +export { SourceFileFilter as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileScanner.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileScanner.js new file mode 100644 index 0000000000000000000000000000000000000000..ffd815cf63e4c139a851c9abc1c1660c7ce5073d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileScanner.js @@ -0,0 +1,31 @@ +import fs from 'fs/promises'; +import path from 'path'; +import SourceFileFilter from './SourceFileFilter.js'; + +class SourceFileScanner { + static async walkSourceFiles(dir, srcPaths, acc = []) { + const entries = await fs.readdir(dir, { + withFileTypes: true + }); + for (const entry of entries) { + const entryPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + if (!SourceFileFilter.shouldEnterDirectory(entryPath, srcPaths)) { + continue; + } + await SourceFileScanner.walkSourceFiles(entryPath, srcPaths, acc); + } else { + if (SourceFileFilter.isSourceFile(entry.name)) { + acc.push(entryPath); + } + } + } + return acc; + } + static async getSourceFiles(srcPaths) { + const files = (await Promise.all(srcPaths.map(srcPath => SourceFileScanner.walkSourceFiles(srcPath, srcPaths)))).flat(); + return new Set(files); + } +} + +export { SourceFileScanner as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileWatcher.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileWatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..a6814673f8b41daaf3a129ad969c670618e81606 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/source/SourceFileWatcher.js @@ -0,0 +1,132 @@ +import fs from 'fs/promises'; +import path from 'path'; +import { subscribe } from '@parcel/watcher'; +import SourceFileFilter from './SourceFileFilter.js'; +import SourceFileScanner from './SourceFileScanner.js'; + +class SourceFileWatcher { + subscriptions = []; + constructor(roots, onChange) { + this.roots = roots; + this.onChange = onChange; + } + async start() { + if (this.subscriptions.length > 0) { + return; + } + const ignore = SourceFileFilter.IGNORED_DIRECTORIES.map(dir => `**/${dir}/**`); + for (const root of this.roots) { + const sub = await subscribe(root, async (err, events) => { + if (err) { + console.error(err); + return; + } + const filtered = await this.normalizeEvents(events); + if (filtered.length > 0) { + await this.onChange(filtered); + } + }, { + ignore + }); + this.subscriptions.push(sub); + } + } + async normalizeEvents(events) { + const directoryCreatePaths = []; + const otherEvents = []; + + // We need to expand directory creates because during rename operations, + // @parcel/watcher emits a directory create event but may not emit individual + // file events for the moved files + await Promise.all(events.map(async event => { + if (event.type === 'create') { + try { + const stats = await fs.stat(event.path); + if (stats.isDirectory()) { + directoryCreatePaths.push(event.path); + return; + } + } catch { + // Path doesn't exist or is inaccessible, treat as file + } + } + otherEvents.push(event); + })); + + // Expand directory create events to find source files inside + let expandedCreateEvents = []; + if (directoryCreatePaths.length > 0) { + try { + const sourceFiles = await SourceFileScanner.getSourceFiles(directoryCreatePaths); + expandedCreateEvents = Array.from(sourceFiles).map(filePath => ({ + type: 'create', + path: filePath + })); + } catch { + // Directories might have been deleted or are inaccessible + } + } + + // Combine original events with expanded directory creates. + // Deduplicate by path to avoid processing the same file twice + // in case @parcel/watcher also emitted individual file events. + const allEvents = [...otherEvents, ...expandedCreateEvents]; + const seenPaths = new Set(); + const deduplicated = []; + for (const event of allEvents) { + const key = `${event.type}:${event.path}`; + if (!seenPaths.has(key)) { + seenPaths.add(key); + deduplicated.push(event); + } + } + return deduplicated.filter(event => { + // Keep all delete events (might be deleted directories that no longer exist) + if (event.type === 'delete') { + return true; + } + // Keep source files + return SourceFileFilter.isSourceFile(event.path); + }); + } + async expandDirectoryDeleteEvents(events, prevKnownFiles) { + const expanded = []; + for (const event of events) { + if (event.type === 'delete' && !SourceFileFilter.isSourceFile(event.path)) { + const dirPath = path.resolve(event.path); + const filesInDirectory = []; + for (const filePath of prevKnownFiles) { + if (SourceFileFilter.isWithinPath(filePath, dirPath)) { + filesInDirectory.push(filePath); + } + } + + // If we found files within this path, it was a directory + if (filesInDirectory.length > 0) { + for (const filePath of filesInDirectory) { + expanded.push({ + type: 'delete', + path: filePath + }); + } + } else { + // Not a directory or no files in it, pass through as-is + expanded.push(event); + } + } else { + // Pass through as-is + expanded.push(event); + } + } + return expanded; + } + async stop() { + await Promise.all(this.subscriptions.map(sub => sub.unsubscribe())); + this.subscriptions = []; + } + [Symbol.dispose]() { + void this.stop(); + } +} + +export { SourceFileWatcher as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/extractor/utils.js b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..12d56ee327c9f1839a9e935fe861deff77f38f01 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/extractor/utils.js @@ -0,0 +1,60 @@ +import path from 'path'; +import { warn } from '../plugin/utils.js'; + +function normalizePathToPosix(filePath) { + // `path.relative` uses OS-specific separators. For stable `.po` references we + // always use POSIX separators, regardless of the OS that ran extraction. + return path.posix.normalize(filePath.split(path.win32.sep).join(path.posix.sep)); +} +const FORBIDDEN_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype']); +function isForbiddenObjectKey(key) { + return FORBIDDEN_OBJECT_KEYS.has(key); +} +function hasLocalesToExtract(config) { + const { + locales + } = config.extract; + return locales === 'infer' || locales.length > 0; +} + +// Essentialls lodash/set, but we avoid this dependency +function setNestedProperty(obj, keyPath, value) { + const keys = keyPath.split('.'); + for (const key of keys) { + if (isForbiddenObjectKey(key)) { + throw new Error(`Invalid message id segment: ${key}`); + } + } + let current = obj; + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (!Object.prototype.hasOwnProperty.call(current, key) || typeof current[key] !== 'object' || current[key] === null) { + current[key] = Object.create(null); + } + current = current[key]; + } + current[keys[keys.length - 1]] = value; +} +function warnAboutMissingReferences(messages) { + const warnedIds = new Set(); + for (const message of messages) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (message.references[0] == null && !warnedIds.has(message.id)) { + warnedIds.add(message.id); + warn(`Missing file reference for extracted message: ${message.id}`); + } + } +} +function localeCompare(a, b) { + return a.localeCompare(b, 'en'); +} +function compareReferences(refA, refB) { + const pathCompare = localeCompare(refA.path, refB.path); + if (pathCompare !== 0) return pathCompare; + return (refA.line ?? 0) - (refB.line ?? 0) || (refA.column ?? 0) - (refB.column ?? 0); +} +function getDefaultProjectRoot() { + return process.cwd(); +} + +export { compareReferences, getDefaultProjectRoot, hasLocalesToExtract, isForbiddenObjectKey, localeCompare, normalizePathToPosix, setNestedProperty, warnAboutMissingReferences }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/index.react-client.js b/e-commerce/node_modules/next-intl/dist/esm/development/index.react-client.js new file mode 100644 index 0000000000000000000000000000000000000000..c5345e2a65181bf31219d72cb2c0bfca72b63584 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/index.react-client.js @@ -0,0 +1,4 @@ +export { useFormatter, useTranslations } from './react-client/index.js'; +export { default as NextIntlClientProvider } from './shared/NextIntlClientProvider.js'; +export { IntlProvider, _useExtracted as useExtracted, useLocale, useMessages, useNow, useTimeZone } from 'use-intl/react'; +export * from 'use-intl/core'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/index.react-server.js b/e-commerce/node_modules/next-intl/dist/esm/development/index.react-server.js new file mode 100644 index 0000000000000000000000000000000000000000..5ce6919de6596273637f8bc3b843fe2b827b5be1 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/index.react-server.js @@ -0,0 +1,9 @@ +export { default as useLocale } from './react-server/useLocale.js'; +export { default as useTranslations } from './react-server/useTranslations.js'; +export { default as useFormatter } from './react-server/useFormatter.js'; +export { default as useNow } from './react-server/useNow.js'; +export { default as useTimeZone } from './react-server/useTimeZone.js'; +export { default as useMessages } from './react-server/useMessages.js'; +export { default as NextIntlClientProvider } from './react-server/NextIntlClientProviderServer.js'; +export { default as useExtracted } from './react-server/useExtracted.js'; +export * from 'use-intl/core'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/middleware.js b/e-commerce/node_modules/next-intl/dist/esm/development/middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..06e40d413e26d20ad2b4ba224715dc1271a4b5ab --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/middleware.js @@ -0,0 +1 @@ +export { default } from './middleware/middleware.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/middleware/getAlternateLinksHeaderValue.js b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/getAlternateLinksHeaderValue.js new file mode 100644 index 0000000000000000000000000000000000000000..6a223d7df79cc3aded110be23d3eb0e9cbb8e652 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/getAlternateLinksHeaderValue.js @@ -0,0 +1,94 @@ +import { normalizeTrailingSlash } from '../shared/utils.js'; +import { getHost, getNormalizedPathname, getLocalePrefixes, isLocaleSupportedOnDomain, applyBasePath, formatTemplatePathname } from './utils.js'; + +/** + * See https://developers.google.com/search/docs/specialty/international/localized-versions + */ +function getAlternateLinksHeaderValue({ + internalTemplateName, + localizedPathnames, + request, + resolvedLocale, + routing +}) { + const normalizedUrl = request.nextUrl.clone(); + const host = getHost(request.headers); + if (host) { + normalizedUrl.port = ''; + normalizedUrl.host = host; + } + normalizedUrl.protocol = request.headers.get('x-forwarded-proto') ?? normalizedUrl.protocol; + normalizedUrl.pathname = getNormalizedPathname(normalizedUrl.pathname, routing.locales, routing.localePrefix); + function getAlternateEntry(url, locale) { + url.pathname = normalizeTrailingSlash(url.pathname); + if (request.nextUrl.basePath) { + url = new URL(url); + url.pathname = applyBasePath(url.pathname, request.nextUrl.basePath); + } + return `<${url.toString()}>; rel="alternate"; hreflang="${locale}"`; + } + function getLocalizedPathname(pathname, locale) { + if (localizedPathnames && typeof localizedPathnames === 'object') { + const sourceTemplate = localizedPathnames[resolvedLocale]; + return formatTemplatePathname(pathname, sourceTemplate ?? internalTemplateName, localizedPathnames[locale] ?? internalTemplateName); + } else { + return pathname; + } + } + const links = getLocalePrefixes(routing.locales, routing.localePrefix, false).flatMap(([locale, prefix]) => { + function prefixPathname(pathname) { + if (pathname === '/') { + return prefix; + } else { + return prefix + pathname; + } + } + let url; + if (routing.domains) { + const domainConfigs = routing.domains.filter(cur => isLocaleSupportedOnDomain(locale, cur)); + return domainConfigs.map(domainConfig => { + url = new URL(normalizedUrl); + url.port = ''; + url.host = domainConfig.domain; + + // Important: Use `normalizedUrl` here, as `url` potentially uses + // a `basePath` that automatically gets applied to the pathname + url.pathname = getLocalizedPathname(normalizedUrl.pathname, locale); + + // Use domain-specific localePrefix mode if available + const domainMode = domainConfig.localePrefix || routing.localePrefix.mode; + if (locale !== domainConfig.defaultLocale || domainMode === 'always') { + url.pathname = prefixPathname(url.pathname); + } + return getAlternateEntry(url, locale); + }); + } else { + let pathname; + if (localizedPathnames && typeof localizedPathnames === 'object') { + pathname = getLocalizedPathname(normalizedUrl.pathname, locale); + } else { + pathname = normalizedUrl.pathname; + } + if (locale !== routing.defaultLocale || routing.localePrefix.mode === 'always') { + pathname = prefixPathname(pathname); + } + url = new URL(pathname, normalizedUrl); + } + return getAlternateEntry(url, locale); + }); + + // Add x-default entry + const shouldAddXDefault = + // For domain-based routing there is no reasonable x-default + !routing.domains || routing.domains.length === 0; + if (shouldAddXDefault) { + const localizedPathname = getLocalizedPathname(normalizedUrl.pathname, routing.defaultLocale); + if (localizedPathname) { + const url = new URL(localizedPathname, normalizedUrl); + links.push(getAlternateEntry(url, 'x-default')); + } + } + return links.join(', '); +} + +export { getAlternateLinksHeaderValue as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/middleware/middleware.js b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..4d81eedcf2a79535b64507736d3bfc9cab876a04 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/middleware.js @@ -0,0 +1,172 @@ +import { NextResponse } from 'next/server'; +import { receiveRoutingConfig } from '../routing/config.js'; +import { HEADER_LOCALE_NAME } from '../shared/constants.js'; +import { matchesPathname, normalizeTrailingSlash, getLocalePrefix, getLocalizedTemplate } from '../shared/utils.js'; +import getAlternateLinksHeaderValue from './getAlternateLinksHeaderValue.js'; +import resolveLocale from './resolveLocale.js'; +import syncCookie from './syncCookie.js'; +import { sanitizePathname, isLocaleSupportedOnDomain, getNormalizedPathname, getPathnameMatch, getInternalTemplate, formatTemplatePathname, formatPathname, getBestMatchingDomain, applyBasePath, getLocaleAsPrefix } from './utils.js'; + +function createMiddleware(routing) { + const resolvedRouting = receiveRoutingConfig(routing); + return function middleware(request) { + let unsafeExternalPathname; + try { + // Resolve potential foreign symbols (e.g. /ja/%E7%B4%84 → /ja/約)) + unsafeExternalPathname = decodeURI(request.nextUrl.pathname); + } catch { + // In case an invalid pathname is encountered, forward + // it to Next.js which in turn responds with a 400 + return NextResponse.next(); + } + + // Sanitize malicious URIs to prevent open redirect attacks due to + // decodeURI doesn't escape encoded backslashes ('%5C' & '%5c') + const externalPathname = sanitizePathname(unsafeExternalPathname); + const { + domain, + locale + } = resolveLocale(resolvedRouting, request.headers, request.cookies, externalPathname); + const hasMatchedDefaultLocale = domain ? domain.defaultLocale === locale : locale === resolvedRouting.defaultLocale; + const domainsConfig = resolvedRouting.domains?.filter(curDomain => isLocaleSupportedOnDomain(locale, curDomain)) || []; + const hasUnknownHost = resolvedRouting.domains != null && !domain; + function next(url) { + const urlObj = new URL(url, request.url); + if (request.nextUrl.basePath) { + urlObj.pathname = applyBasePath(urlObj.pathname, request.nextUrl.basePath); + } + const headers = new Headers(request.headers); + headers.set(HEADER_LOCALE_NAME, locale); + const isRewriteNecessary = normalizeTrailingSlash(request.nextUrl.pathname) !== normalizeTrailingSlash(urlObj.pathname); + if (isRewriteNecessary) { + return NextResponse.rewrite(urlObj, { + request: { + headers + } + }); + } else { + return NextResponse.next({ + request: { + headers + } + }); + } + } + function redirect(url, redirectDomain) { + const urlObj = new URL(url, request.url); + urlObj.pathname = normalizeTrailingSlash(urlObj.pathname); + if (domainsConfig.length > 0 && !redirectDomain && domain) { + const bestMatchingDomain = getBestMatchingDomain(domain, locale, domainsConfig); + if (bestMatchingDomain) { + redirectDomain = bestMatchingDomain.domain; + const redirectDomainMode = bestMatchingDomain.localePrefix || resolvedRouting.localePrefix.mode; + if (bestMatchingDomain.defaultLocale === locale && redirectDomainMode === 'as-needed') { + urlObj.pathname = getNormalizedPathname(urlObj.pathname, resolvedRouting.locales, resolvedRouting.localePrefix); + } + } + } + if (redirectDomain) { + urlObj.host = redirectDomain; + if (request.headers.get('x-forwarded-host')) { + urlObj.protocol = request.headers.get('x-forwarded-proto') ?? request.nextUrl.protocol; + const redirectDomainPort = redirectDomain.split(':')[1]; + urlObj.port = redirectDomainPort ?? request.headers.get('x-forwarded-port') ?? ''; + } + } + if (request.nextUrl.basePath) { + urlObj.pathname = applyBasePath(urlObj.pathname, request.nextUrl.basePath); + } + hasRedirected = true; + return NextResponse.redirect(urlObj.toString()); + } + const unprefixedExternalPathname = getNormalizedPathname(externalPathname, resolvedRouting.locales, resolvedRouting.localePrefix); + const pathnameMatch = getPathnameMatch(externalPathname, resolvedRouting.locales, resolvedRouting.localePrefix, domain); + const hasLocalePrefix = pathnameMatch != null; + + // Use domain-specific localePrefix mode if available, otherwise use global mode + const effectiveLocalePrefixMode = domain?.localePrefix || resolvedRouting.localePrefix.mode; + const isUnprefixedRouting = effectiveLocalePrefixMode === 'never' || hasMatchedDefaultLocale && effectiveLocalePrefixMode === 'as-needed'; + let response; + let internalTemplateName; + let hasRedirected; + let unprefixedInternalPathname = unprefixedExternalPathname; + const pathnames = resolvedRouting.pathnames; + if (pathnames) { + let resolvedTemplateLocale; + [resolvedTemplateLocale, internalTemplateName] = getInternalTemplate(pathnames, unprefixedExternalPathname, locale); + if (internalTemplateName) { + const pathnameConfig = pathnames[internalTemplateName]; + const localeTemplate = getLocalizedTemplate(pathnameConfig, locale, internalTemplateName); + if (matchesPathname(localeTemplate, unprefixedExternalPathname)) { + unprefixedInternalPathname = formatTemplatePathname(unprefixedExternalPathname, localeTemplate, internalTemplateName); + } else { + let sourceTemplate; + if (resolvedTemplateLocale) { + // A localized pathname from another locale has matched + sourceTemplate = getLocalizedTemplate(pathnameConfig, resolvedTemplateLocale, internalTemplateName); + } else { + // An internal pathname has matched that + // doesn't have a localized pathname + sourceTemplate = internalTemplateName; + } + const localePrefix = isUnprefixedRouting ? undefined : getLocalePrefix(locale, resolvedRouting.localePrefix); + const template = formatTemplatePathname(unprefixedExternalPathname, sourceTemplate, localeTemplate); + response = redirect(formatPathname(template, localePrefix, request.nextUrl.search)); + } + } + } + if (!response) { + if (unprefixedInternalPathname === '/' && !hasLocalePrefix) { + if (isUnprefixedRouting) { + response = next(formatPathname(unprefixedInternalPathname, getLocaleAsPrefix(locale), request.nextUrl.search)); + } else { + response = redirect(formatPathname(unprefixedExternalPathname, getLocalePrefix(locale, resolvedRouting.localePrefix), request.nextUrl.search)); + } + } else { + const internalHref = formatPathname(unprefixedInternalPathname, getLocaleAsPrefix(locale), request.nextUrl.search); + if (hasLocalePrefix) { + const externalHref = formatPathname(unprefixedExternalPathname, pathnameMatch.prefix, request.nextUrl.search); + if (effectiveLocalePrefixMode === 'never') { + response = redirect(formatPathname(unprefixedExternalPathname, undefined, request.nextUrl.search)); + } else if (pathnameMatch.exact) { + if (hasMatchedDefaultLocale && isUnprefixedRouting) { + response = redirect(formatPathname(unprefixedExternalPathname, undefined, request.nextUrl.search)); + } else { + if (resolvedRouting.domains) { + const pathDomain = getBestMatchingDomain(domain, pathnameMatch.locale, domainsConfig); + if (domain?.domain !== pathDomain?.domain && !hasUnknownHost) { + response = redirect(externalHref, pathDomain?.domain); + } else { + response = next(internalHref); + } + } else { + response = next(internalHref); + } + } + } else { + response = redirect(externalHref); + } + } else { + if (isUnprefixedRouting) { + response = next(internalHref); + } else { + response = redirect(formatPathname(unprefixedExternalPathname, getLocalePrefix(locale, resolvedRouting.localePrefix), request.nextUrl.search)); + } + } + } + } + syncCookie(request, response, locale, resolvedRouting, domain); + if (!hasRedirected && effectiveLocalePrefixMode !== 'never' && resolvedRouting.alternateLinks && resolvedRouting.locales.length > 1) { + response.headers.set('Link', getAlternateLinksHeaderValue({ + routing: resolvedRouting, + internalTemplateName, + localizedPathnames: internalTemplateName != null && pathnames ? pathnames[internalTemplateName] : undefined, + request, + resolvedLocale: locale + })); + } + return response; + }; +} + +export { createMiddleware as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/middleware/resolveLocale.js b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/resolveLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..63e445c5d5e210ace80c10878489650189ae3631 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/resolveLocale.js @@ -0,0 +1,129 @@ +import { match } from '@formatjs/intl-localematcher'; +import Negotiator from 'negotiator'; +import { getPathnameMatch, isLocaleSupportedOnDomain, getHost } from './utils.js'; + +function findDomainFromHost(requestHeaders, domains) { + const host = getHost(requestHeaders); + if (host) { + return domains.find(cur => cur.domain === host); + } + return undefined; +} +function orderLocales(locales) { + // Workaround for https://github.com/formatjs/formatjs/issues/4469 + return locales.slice().sort((a, b) => b.length - a.length); +} +function mapToProvidedLocale(locales, locale) { + return locales.find(cur => cur.toLowerCase() === locale.toLowerCase()); +} +function getAcceptLanguageLocale(requestHeaders, locales, defaultLocale) { + let locale; + const languages = new Negotiator({ + headers: { + 'accept-language': requestHeaders.get('accept-language') || undefined + } + }).languages(); + try { + const orderedLocales = orderLocales(locales); + locale = mapToProvidedLocale(locales, match(languages, orderedLocales, defaultLocale)); + } catch { + // Invalid language + } + return locale; +} +function getLocaleFromCookie(routing, requestCookies) { + if (routing.localeCookie && requestCookies.has(routing.localeCookie.name)) { + const value = requestCookies.get(routing.localeCookie.name)?.value; + if (value && routing.locales.includes(value)) { + return value; + } + } +} +function resolveLocaleFromPrefix(routing, requestHeaders, requestCookies, pathname) { + let locale; + + // Prio 1: Use route prefix + if (pathname) { + locale = getPathnameMatch(pathname, routing.locales, routing.localePrefix)?.locale; + } + + // Prio 2: Use existing cookie + if (!locale && routing.localeDetection) { + locale = getLocaleFromCookie(routing, requestCookies); + } + + // Prio 3: Use the `accept-language` header + if (!locale && routing.localeDetection) { + locale = getAcceptLanguageLocale(requestHeaders, routing.locales, routing.defaultLocale); + } + + // Prio 4: Use default locale + if (!locale) { + locale = routing.defaultLocale; + } + return locale; +} +function resolveLocaleFromDomain(routing, requestHeaders, requestCookies, pathname) { + const domains = routing.domains; + const domain = findDomainFromHost(requestHeaders, domains); + if (!domain) { + return { + locale: resolveLocaleFromPrefix(routing, requestHeaders, requestCookies, pathname) + }; + } + let locale; + + // Prio 1: Use route prefix + if (pathname) { + const prefixLocale = getPathnameMatch(pathname, routing.locales, routing.localePrefix, domain)?.locale; + if (prefixLocale) { + if (isLocaleSupportedOnDomain(prefixLocale, domain)) { + locale = prefixLocale; + } else { + // Causes a redirect to a domain that supports the locale + return { + locale: prefixLocale, + domain + }; + } + } + } + + // Prio 2: Use existing cookie + if (!locale && routing.localeDetection) { + const cookieLocale = getLocaleFromCookie(routing, requestCookies); + if (cookieLocale) { + if (isLocaleSupportedOnDomain(cookieLocale, domain)) { + locale = cookieLocale; + } + } + } + + // Prio 3: Use the `accept-language` header + if (!locale && routing.localeDetection) { + const headerLocale = getAcceptLanguageLocale(requestHeaders, domain.locales, domain.defaultLocale); + if (headerLocale) { + locale = headerLocale; + } + } + + // Prio 4: Use default locale + if (!locale) { + locale = domain.defaultLocale; + } + return { + locale, + domain + }; +} +function resolveLocale(routing, requestHeaders, requestCookies, pathname) { + if (routing.domains) { + return resolveLocaleFromDomain(routing, requestHeaders, requestCookies, pathname); + } else { + return { + locale: resolveLocaleFromPrefix(routing, requestHeaders, requestCookies, pathname) + }; + } +} + +export { resolveLocale as default, getAcceptLanguageLocale }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/middleware/syncCookie.js b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/syncCookie.js new file mode 100644 index 0000000000000000000000000000000000000000..ad3f61bad029835a9bd2579fe698d516d4afa66d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/syncCookie.js @@ -0,0 +1,42 @@ +import { getAcceptLanguageLocale } from './resolveLocale.js'; + +function syncCookie(request, response, locale, routing, domain) { + if (!routing.localeCookie) return; + + // Only document requests indicate that the user is actually + // navigating to a page—in contrast to background requests of the + // client-side router like prefetches and cache revalidations. + // E.g. as of Next.js 16.3, the router revalidates previously + // visited routes after a navigation, including routes of a locale + // the user has just switched away from. Updating the cookie based + // on such a request would overwrite the locale that was just set + // when switching the locale. Note that Next.js strips router + // headers like `Next-Router-Prefetch` before invoking the + // middleware, therefore `Sec-Fetch-Dest` is used to detect + // background requests. Locale switches via a soft navigation + // update the cookie on the client side. + const secFetchDest = request.headers.get('sec-fetch-dest'); + if (secFetchDest != null && secFetchDest !== 'document') return; + const { + name, + ...rest + } = routing.localeCookie; + const hasLocaleCookie = request.cookies.has(name); + const hasOutdatedCookie = hasLocaleCookie && request.cookies.get(name)?.value !== locale; + if (hasOutdatedCookie) { + response.cookies.set(name, locale, { + path: request.nextUrl.basePath || undefined, + ...rest + }); + } else if (!hasLocaleCookie) { + const acceptLanguageLocale = getAcceptLanguageLocale(request.headers, domain?.locales || routing.locales, routing.defaultLocale); + if (acceptLanguageLocale !== locale) { + response.cookies.set(name, locale, { + path: request.nextUrl.basePath || undefined, + ...rest + }); + } + } +} + +export { syncCookie as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/middleware/utils.js b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..42bc49e2c2f42eac589b1f5adfed6d8124c61205 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/middleware/utils.js @@ -0,0 +1,202 @@ +import { normalizeTrailingSlash, getSortedPathnames, matchesPathname, prefixPathname, getLocalePrefix, templateToRegex, getLocalizedTemplate } from '../shared/utils.js'; + +function getInternalTemplate(pathnames, pathname, locale) { + const sortedPathnames = getSortedPathnames(Object.keys(pathnames)); + + // Try to find a localized pathname that matches + for (const internalPathname of sortedPathnames) { + const localizedPathnamesOrPathname = pathnames[internalPathname]; + if (typeof localizedPathnamesOrPathname === 'string') { + const localizedPathname = localizedPathnamesOrPathname; + if (matchesPathname(localizedPathname, pathname)) { + return [undefined, internalPathname]; + } + } else { + // Prefer the entry with the current locale in case multiple + // localized pathnames match the current pathname + const sortedEntries = Object.entries(localizedPathnamesOrPathname); + const curLocaleIndex = sortedEntries.findIndex(([entryLocale]) => entryLocale === locale); + if (curLocaleIndex > 0) { + sortedEntries.unshift(sortedEntries.splice(curLocaleIndex, 1)[0]); + } + for (const [entryLocale] of sortedEntries) { + const localizedTemplate = getLocalizedTemplate(pathnames[internalPathname], entryLocale, internalPathname); + if (matchesPathname(localizedTemplate, pathname)) { + return [entryLocale, internalPathname]; + } + } + } + } + + // Try to find an internal pathname that matches (this can be the case + // if all localized pathnames are different from the internal pathnames) + for (const internalPathname of Object.keys(pathnames)) { + if (matchesPathname(internalPathname, pathname)) { + return [undefined, internalPathname]; + } + } + + // No match + return [undefined, undefined]; +} +function formatTemplatePathname(sourcePathname, sourceTemplate, targetTemplate, prefix) { + const params = getRouteParams(sourceTemplate, sourcePathname); + let targetPathname = ''; + targetPathname += formatPathnameTemplate(targetTemplate, params); + + // A pathname with an optional catchall like `/categories/[[...slug]]` + // should be normalized to `/categories` if the catchall is not present + // and no trailing slash is configured + targetPathname = normalizeTrailingSlash(targetPathname); + return targetPathname; +} + +/** + * Removes potential prefixes from the pathname. + */ +function getNormalizedPathname(pathname, locales, localePrefix) { + // Add trailing slash for consistent handling + // both for the root as well as nested paths + if (!pathname.endsWith('/')) { + pathname += '/'; + } + const localePrefixes = getLocalePrefixes(locales, localePrefix); + const regex = new RegExp(`^(${localePrefixes.map(([, prefix]) => prefix.replaceAll('/', '\\/')).join('|')})/(.*)`, 'i'); + const match = pathname.match(regex); + let result = match ? '/' + match[2] : pathname; + if (result !== '/') { + result = normalizeTrailingSlash(result); + } + return result; +} +function getLocalePrefixes(locales, localePrefix, sort = true) { + const prefixes = locales.map(locale => [locale, getLocalePrefix(locale, localePrefix)]); + if (sort) { + // More specific ones first + prefixes.sort((a, b) => b[1].length - a[1].length); + } + return prefixes; +} +function getPathnameMatch(pathname, locales, localePrefix, domain) { + const localePrefixes = getLocalePrefixes(locales, localePrefix); + + // Sort to prioritize domain locales + if (domain) { + localePrefixes.sort(([localeA], [localeB]) => { + if (localeA === domain.defaultLocale) return -1; + if (localeB === domain.defaultLocale) return 1; + const isLocaleAInDomain = domain.locales.includes(localeA); + const isLocaleBInDomain = domain.locales.includes(localeB); + if (isLocaleAInDomain && !isLocaleBInDomain) return -1; + if (!isLocaleAInDomain && isLocaleBInDomain) return 1; + return 0; + }); + } + for (const [locale, prefix] of localePrefixes) { + let exact, matches; + if (pathname === prefix || pathname.startsWith(prefix + '/')) { + exact = matches = true; + } else { + const normalizedPathname = pathname.toLowerCase(); + const normalizedPrefix = prefix.toLowerCase(); + if (normalizedPathname === normalizedPrefix || normalizedPathname.startsWith(normalizedPrefix + '/')) { + exact = false; + matches = true; + } + } + if (matches) { + return { + locale, + prefix, + matchedPrefix: pathname.slice(0, prefix.length), + exact + }; + } + } +} +function getRouteParams(template, pathname) { + const normalizedPathname = normalizeTrailingSlash(pathname); + const normalizedTemplate = normalizeTrailingSlash(template); + const regex = templateToRegex(normalizedTemplate); + const match = regex.exec(normalizedPathname); + if (!match) return undefined; + const params = {}; + const keys = normalizedTemplate.match(/\[([^\]]+)\]/g) ?? []; + for (let i = 1; i < match.length; i++) { + const rawKey = keys[i - 1]; + if (!rawKey) continue; + const key = rawKey.replace(/[[\]]/g, ''); + const value = match[i] ?? ''; + params[key] = value; + } + return params; +} +function formatPathnameTemplate(template, params) { + if (!params) return template; + + // Simplify syntax for optional catchall ('[[...slug]]') so + // we can replace the value with simple interpolation + template = template.replace(/\[\[/g, '[').replace(/\]\]/g, ']'); + let result = template; + Object.entries(params).forEach(([key, value]) => { + result = result.replace(`[${key}]`, () => value); + }); + return result; +} +function formatPathname(pathname, prefix, search) { + let result = pathname; + if (prefix) { + result = prefixPathname(prefix, result); + } + if (search) { + result += search; + } + return result; +} +function getHost(requestHeaders) { + return requestHeaders.get('x-forwarded-host') ?? requestHeaders.get('host') ?? undefined; +} +function isLocaleSupportedOnDomain(locale, domain) { + return domain.defaultLocale === locale || domain.locales.includes(locale); +} +function getBestMatchingDomain(curHostDomain, locale, domainsConfig) { + let domainConfig; + + // Prio 1: Stay on current domain + if (curHostDomain && isLocaleSupportedOnDomain(locale, curHostDomain)) { + domainConfig = curHostDomain; + } + + // Prio 2: Use alternative domain with matching default locale + if (!domainConfig) { + domainConfig = domainsConfig.find(cur => cur.defaultLocale === locale); + } + + // Prio 3: Use alternative domain that supports the locale + if (!domainConfig) { + domainConfig = domainsConfig.find(cur => cur.locales.includes(locale)); + } + return domainConfig; +} +function applyBasePath(pathname, basePath) { + return normalizeTrailingSlash(basePath + pathname); +} +function getLocaleAsPrefix(locale) { + return `/${locale}`; +} +function sanitizePathname(pathname) { + // Sanitize malicious URIs, e.g.: + // '/en/\\example.org' → '/en/%5Cexample.org' (backslash → %5C) + // '/en/\t/example.org' → '/en/example.org' (WHATWG-stripped TAB) + // '/en/\n/example.org' → '/en/example.org' (WHATWG-stripped LF) + // '/en/\r/example.org' → '/en/example.org' (WHATWG-stripped CR) + // '/en////example.org' → '/en/example.org' (consecutive slashes) + // + // U+0009/000A/000D are silently stripped by the WHATWG URL parser + // (https://url.spec.whatwg.org/#concept-url-parser). Without removing + // them here, a decoded TAB in a segment separator position causes + // new URL("/\t/host", base) to collapse to "//host" → open redirect. + return pathname.replace(/\\/g, '%5C').replace(/[\t\n\r]/g, '').replace(/\/+/g, '/'); +} + +export { applyBasePath, formatPathname, formatPathnameTemplate, formatTemplatePathname, getBestMatchingDomain, getHost, getInternalTemplate, getLocaleAsPrefix, getLocalePrefixes, getNormalizedPathname, getPathnameMatch, getRouteParams, isLocaleSupportedOnDomain, sanitizePathname }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation.react-client.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation.react-client.js new file mode 100644 index 0000000000000000000000000000000000000000..d57c76294c4af95047eba698f62fed13632a5426 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation.react-client.js @@ -0,0 +1 @@ +export { default as createNavigation } from './navigation/react-client/createNavigation.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation.react-server.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation.react-server.js new file mode 100644 index 0000000000000000000000000000000000000000..f4878e9a4c70dc58d91abe1e1aad9906688ab2ef --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation.react-server.js @@ -0,0 +1 @@ +export { default as createNavigation } from './navigation/react-server/createNavigation.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-client/createNavigation.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-client/createNavigation.js new file mode 100644 index 0000000000000000000000000000000000000000..3e0e4c5ebad876a6c4833c7ce9d1289783839ec8 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-client/createNavigation.js @@ -0,0 +1,79 @@ +import { useRouter } from 'next/navigation'; +import { useMemo } from 'react'; +import { useLocale } from 'use-intl'; +import createSharedNavigationFns from '../shared/createSharedNavigationFns.js'; +import syncLocaleCookie from '../shared/syncLocaleCookie.js'; +import { getRoute } from '../shared/utils.js'; +import useBasePathname from './useBasePathname.js'; + +function createNavigation(routing) { + const { + Link, + config, + getPathname, + ...redirects + } = createSharedNavigationFns(useLocale, routing); + + /** @see https://next-intl.dev/docs/routing/navigation#usepathname */ + function usePathname() { + const pathname = useBasePathname(config); + const locale = useLocale(); + + // @ts-expect-error -- Mirror the behavior from Next.js, where `null` is returned when `usePathname` is used outside of Next, but the types indicate that a string is always returned. + return useMemo(() => pathname && + // @ts-expect-error -- This is fine + config.pathnames ? getRoute(locale, pathname, + // @ts-expect-error -- This is fine + config.pathnames) : pathname, [locale, pathname]); + } + function useRouter$1() { + const router = useRouter(); + const curLocale = useLocale(); + return useMemo(() => { + function createHandler(fn) { + return function handler(href, options) { + const { + locale: nextLocale, + ...rest + } = options || {}; + const pathname = getPathname({ + href, + locale: nextLocale || curLocale, + // Always include a prefix when changing locales. Theoretically, + // this is only necessary for the case described in #2020. However, + // the full detection is rather expensive, and this behavior is + // consistent with the `Link` component. The downside is an + // additional redirect for users in other situations. Locale + // changes should be rare though, so this might be fine. + forcePrefix: nextLocale != null || undefined + }); + const args = [pathname]; + if (Object.keys(rest).length > 0) { + // @ts-expect-error -- This is fine + args.push(rest); + } + syncLocaleCookie(config.localeCookie, curLocale, nextLocale); + fn(...args); + }; + } + return { + ...router, + /** @see https://next-intl.dev/docs/routing/navigation#userouter */ + push: createHandler(router.push), + /** @see https://next-intl.dev/docs/routing/navigation#userouter */ + replace: createHandler(router.replace), + /** @see https://next-intl.dev/docs/routing/navigation#userouter */ + prefetch: createHandler(router.prefetch) + }; + }, [curLocale, router]); + } + return { + ...redirects, + Link, + usePathname, + useRouter: useRouter$1, + getPathname + }; +} + +export { createNavigation as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-client/useBasePathname.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-client/useBasePathname.js new file mode 100644 index 0000000000000000000000000000000000000000..241d4f565af1022dd17abf8e3a0ab64d94ac3eec --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-client/useBasePathname.js @@ -0,0 +1,36 @@ +import { usePathname } from 'next/navigation'; +import { useMemo } from 'react'; +import { useLocale } from 'use-intl'; +import { hasPathnamePrefixed, unprefixPathname, getLocalePrefix, getLocaleAsPrefix } from '../../shared/utils.js'; + +function useBasePathname(config) { + // The types aren't entirely correct here. Outside of Next.js + // `useParams` can be called, but the return type is `null`. + + // Notes on `useNextPathname`: + // - Types aren't entirely correct. Outside of Next.js the + // hook will return `null` (e.g. unit tests) + // - A base path is stripped from the result + // - Rewrites *are* taken into account (i.e. the pathname + // that the user sees in the browser is returned) + const pathname = usePathname(); + const locale = useLocale(); + return useMemo(() => { + if (!pathname) return pathname; + let unlocalizedPathname = pathname; + const prefix = getLocalePrefix(locale, config.localePrefix); + const isPathnamePrefixed = hasPathnamePrefixed(prefix, pathname); + if (isPathnamePrefixed) { + unlocalizedPathname = unprefixPathname(pathname, prefix); + } else if (config.localePrefix.mode !== 'never' && config.localePrefix.prefixes) { + // Workaround for https://github.com/vercel/next.js/issues/73085 + const localeAsPrefix = getLocaleAsPrefix(locale); + if (hasPathnamePrefixed(localeAsPrefix, pathname)) { + unlocalizedPathname = unprefixPathname(pathname, localeAsPrefix); + } + } + return unlocalizedPathname; + }, [config.localePrefix, locale, pathname]); +} + +export { useBasePathname as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-server/createNavigation.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-server/createNavigation.js new file mode 100644 index 0000000000000000000000000000000000000000..bdda67fe919a11bfa801a26a6af6f3ad07b9300f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-server/createNavigation.js @@ -0,0 +1,22 @@ +import createSharedNavigationFns from '../shared/createSharedNavigationFns.js'; +import getServerLocale from './getServerLocale.js'; + +function createNavigation(routing) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { + config, + ...fns + } = createSharedNavigationFns(getServerLocale, routing); + function notSupported(hookName) { + return () => { + throw new Error(`\`${hookName}\` is not supported in Server Components. You can use this hook if you convert the calling component to a Client Component.`); + }; + } + return { + ...fns, + usePathname: notSupported('usePathname'), + useRouter: notSupported('useRouter') + }; +} + +export { createNavigation as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-server/getServerLocale.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-server/getServerLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..91a16b8824c6afb49d2d4ac368fa03177a2c5bc7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/react-server/getServerLocale.js @@ -0,0 +1,12 @@ +import getConfig from '../../server/react-server/getConfig.js'; + +/** + * This is only moved to a separate module for easier mocking in + * `../createNavigatoin.test.tsx` in order to avoid suspending. + */ +async function getServerLocale() { + const config = await getConfig(); + return config.locale; +} + +export { getServerLocale as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/BaseLink.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/BaseLink.js new file mode 100644 index 0000000000000000000000000000000000000000..bf5c92c44fe9ca74bd9471c56d4dbd6033198c05 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/BaseLink.js @@ -0,0 +1,64 @@ +"use client"; +import NextLink from 'next/link'; +import { forwardRef } from 'react'; +import { useLocale } from 'use-intl'; +import syncLocaleCookie from './syncLocaleCookie.js'; +import { jsx } from 'react/jsx-runtime'; + +// Somehow the types for `next/link` don't work as expected +// when `moduleResolution: "nodenext"` is used. +const Link = NextLink; + +// Links that change the locale are handled in a separate component, +// since they require additional handling for syncing the locale cookie. +function LocaleChangingLink({ + curLocale, + linkRef, + locale, + localeCookie, + onClick, + prefetch, + ...rest +}) { + function onLinkClick(event) { + // Even though we force a prefix when changing locales, + // this could be a cache hit of the client-side router, + // therefore we sync the cookie to ensure it's up to date. + syncLocaleCookie(localeCookie, curLocale, locale); + if (onClick) onClick(event); + } + if (prefetch && "development" !== 'production') { + console.error('The `prefetch` prop is currently not supported when using the `locale` prop on `Link` to switch the locale.`'); + } + return /*#__PURE__*/jsx(Link, { + ref: linkRef, + hrefLang: locale, + onClick: onLinkClick, + prefetch: false, + ...rest + }); +} +function BaseLink({ + locale, + localeCookie, + ...rest +}, ref) { + const curLocale = useLocale(); + const isChangingLocale = locale != null && locale !== curLocale; + if (isChangingLocale) { + return /*#__PURE__*/jsx(LocaleChangingLink, { + curLocale: curLocale, + linkRef: ref, + locale: locale, + localeCookie: localeCookie, + ...rest + }); + } + return /*#__PURE__*/jsx(Link, { + ref: ref, + ...rest + }); +} +var BaseLink$1 = /*#__PURE__*/forwardRef(BaseLink); + +export { BaseLink$1 as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/createSharedNavigationFns.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/createSharedNavigationFns.js new file mode 100644 index 0000000000000000000000000000000000000000..0bbc764ff223e10510f6244e4a2cc25f920e693d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/createSharedNavigationFns.js @@ -0,0 +1,105 @@ +import { redirect, permanentRedirect } from 'next/navigation'; +import { forwardRef } from 'react'; +import { receiveRoutingConfig } from '../../routing/config.js'; +import use from '../../shared/use.js'; +import { isLocalizableHref, isPromise } from '../../shared/utils.js'; +import BaseLink from './BaseLink.js'; +import { validateReceivedConfig, serializeSearchParams, compileLocalizedPathname, applyPathnamePrefix, normalizeNameOrNameWithParams } from './utils.js'; +import { jsx } from 'react/jsx-runtime'; + +/** + * Shared implementations for `react-server` and `react-client` + */ +function createSharedNavigationFns(getLocale, routing) { + const config = receiveRoutingConfig(routing || {}); + { + validateReceivedConfig(config); + } + const pathnames = config.pathnames; + function Link({ + href, + locale, + ...rest + }, ref) { + let pathname, params; + if (typeof href === 'object') { + pathname = href.pathname; + // @ts-expect-error -- This is ok + params = href.params; + } else { + pathname = href; + } + + // @ts-expect-error -- This is ok + const isLocalizable = isLocalizableHref(href); + const localePromiseOrValue = getLocale(); + const curLocale = isPromise(localePromiseOrValue) ? use(localePromiseOrValue) : localePromiseOrValue; + const finalPathname = isLocalizable ? getPathname({ + locale: locale || curLocale, + // @ts-expect-error -- This is ok + href: pathnames == null ? pathname : { + pathname, + params + }, + // Always include a prefix when changing locales + forcePrefix: locale != null || undefined + }) : pathname; + return /*#__PURE__*/jsx(BaseLink, { + ref: ref + // @ts-expect-error -- This is ok + , + href: typeof href === 'object' ? { + ...href, + pathname: finalPathname + } : finalPathname, + locale: locale, + localeCookie: config.localeCookie, + ...rest + }); + } + const LinkWithRef = /*#__PURE__*/forwardRef(Link); + function getPathname(args) { + const { + forcePrefix, + href, + locale + } = args; + let pathname; + if (pathnames == null) { + if (typeof href === 'object') { + pathname = href.pathname; + if (href.query) { + pathname += serializeSearchParams(href.query); + } + } else { + pathname = href; + } + } else { + pathname = compileLocalizedPathname({ + locale, + // @ts-expect-error -- This is ok + ...normalizeNameOrNameWithParams(href), + // @ts-expect-error -- This is ok + pathnames: config.pathnames + }); + } + return applyPathnamePrefix(pathname, locale, config, forcePrefix); + } + function getRedirectFn(fn) { + /** @see https://next-intl.dev/docs/routing/navigation#redirect */ + return function redirectFn(args, ...rest) { + return fn(getPathname(args), ...rest); + }; + } + const redirect$1 = getRedirectFn(redirect); + const permanentRedirect$1 = getRedirectFn(permanentRedirect); + return { + config, + Link: LinkWithRef, + redirect: redirect$1, + permanentRedirect: permanentRedirect$1, + getPathname + }; +} + +export { createSharedNavigationFns as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/syncLocaleCookie.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/syncLocaleCookie.js new file mode 100644 index 0000000000000000000000000000000000000000..6eb5fe53b37d27368fb406dee92577a6c1eb6ab6 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/syncLocaleCookie.js @@ -0,0 +1,41 @@ +import { getBasePath } from './utils.js'; + +/** + * We have to keep the cookie value in sync as Next.js might + * skip a request to the server due to its router cache. + * See https://github.com/amannn/next-intl/issues/786. + */ +function syncLocaleCookie(localeCookie, locale, nextLocale) { + const isSwitchingLocale = nextLocale !== locale && nextLocale != null; + if (!localeCookie || !isSwitchingLocale) { + return; + } + const { + name, + ...rest + } = localeCookie; + if (!rest.path) { + rest.path = getBasePath() || '/'; + } + let localeCookieString = `${name}=${nextLocale};`; + for (const [key, value] of Object.entries(rest)) { + // Map object properties to cookie properties. + // Interestingly, `maxAge` corresponds to `max-age`, + // while `sameSite` corresponds to `SameSite`. + // Also, keys are case-insensitive. + const targetKey = key === 'maxAge' ? 'max-age' : key; + localeCookieString += `${targetKey}`; + if (typeof value !== 'boolean') { + localeCookieString += '=' + value; + } + + // A trailing ";" is allowed by browsers + localeCookieString += ';'; + } + + // Note that writing to `document.cookie` doesn't overwrite all + // cookies, but only the ones referenced via the name here. + document.cookie = localeCookieString; +} + +export { syncLocaleCookie as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/utils.js b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..898e30395745dd188659009f2e2e8ac0b2cf3447 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/navigation/shared/utils.js @@ -0,0 +1,169 @@ +import { getSortedPathnames, matchesPathname, isLocalizableHref, prefixPathname, getLocalizedTemplate, normalizeTrailingSlash, getLocalePrefix } from '../../shared/utils.js'; + +// Minor false positive: A route that has both optional and +// required params will allow optional params. + +// For `Link` + +// For `getPathname` (hence also its consumers: `redirect`, `useRouter`, …) + +function normalizeNameOrNameWithParams(href) { + return typeof href === 'string' ? { + pathname: href + } : href; +} +function serializeSearchParams(searchParams) { + function serializeValue(value) { + return String(value); + } + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(searchParams)) { + if (Array.isArray(value)) { + value.forEach(cur => { + urlSearchParams.append(key, serializeValue(cur)); + }); + } else { + urlSearchParams.set(key, serializeValue(value)); + } + } + return '?' + urlSearchParams.toString(); +} +function compileLocalizedPathname({ + pathname, + locale, + params, + pathnames, + query +}) { + function compilePath(value) { + const pathnameConfig = pathnames[value]; + let compiled; + if (pathnameConfig) { + const template = getLocalizedTemplate(pathnameConfig, locale, value); + compiled = template; + if (params) { + Object.entries(params).forEach(([key, paramValue]) => { + let regexp, replacer; + if (Array.isArray(paramValue)) { + regexp = `(\\[)?\\[...${key}\\](\\])?`; + replacer = paramValue.map(v => String(v)).join('/'); + } else { + regexp = `\\[${key}\\]`; + replacer = String(paramValue); + } + compiled = compiled.replace(new RegExp(regexp, 'g'), () => replacer); + }); + } + + // Clean up optional catch-all segments that were not replaced + compiled = compiled.replace(/\[\[\.\.\..+\]\]/g, ''); + if (compiled.includes('[')) { + // Next.js throws anyway, therefore better provide a more helpful error message + throw new Error(`Insufficient params provided for localized pathname.\nTemplate: ${template}\nParams: ${JSON.stringify(params)}`); + } + compiled = encodePathname(compiled); + } else { + // Unknown pathnames + compiled = value; + } + compiled = normalizeTrailingSlash(compiled); + if (query) { + // This also encodes non-ASCII characters by + // using `new URLSearchParams()` internally + compiled += serializeSearchParams(query); + } + return compiled; + } + if (typeof pathname === 'string') { + return compilePath(pathname); + } else { + const { + pathname: internalPathname, + ...rest + } = pathname; + const compiled = compilePath(internalPathname); + const result = { + ...rest, + pathname: compiled + }; + return result; + } +} +function encodePathname(pathname) { + // Generally, to comply with RFC 3986 and Google's best practices for URL structures + // (https://developers.google.com/search/docs/crawling-indexing/url-structure), + // we should always encode non-ASCII characters. + // + // There are two places where next-intl interacts with potentially non-ASCII URLs: + // 1. Middleware: When mapping a localized pathname to a non-localized pathname internally + // 2. Navigation APIs: When generating a URLs to be used for & friends + // + // Next.js normalizes incoming pathnames to always be encoded, therefore we can safely + // decode them there (see middleware.tsx). On the other hand, Next.js doesn't consistently + // encode non-ASCII characters that are passed to navigation APIs: + // 1. doesn't encode non-ASCII characters + // 2. useRouter() uses `new URL()` internally, which will encode—but only if necessary + // 3. redirect() uses useRouter() on the client, but on the server side only + // assigns the location header without encoding. + // + // In addition to this, for getPathname() we need to encode non-ASCII characters. + // + // Therefore, the bottom line is that next-intl should take care of encoding non-ASCII + // characters in all cases, but can rely on `new URL()` to not double-encode characters. + return new URL(pathname, 'http://l').pathname; +} +function getRoute(locale, pathname, pathnames) { + const sortedPathnames = getSortedPathnames(Object.keys(pathnames)); + const decoded = decodeURI(pathname); + for (const internalPathname of sortedPathnames) { + const localizedPathnamesOrPathname = pathnames[internalPathname]; + if (typeof localizedPathnamesOrPathname === 'string') { + const localizedPathname = localizedPathnamesOrPathname; + if (matchesPathname(localizedPathname, decoded)) { + return internalPathname; + } + } else { + if (matchesPathname(getLocalizedTemplate(localizedPathnamesOrPathname, locale, internalPathname), decoded)) { + return internalPathname; + } + } + } + return pathname; +} +function getBasePath() { + try { + // Provided via `env` setting in `next.config.js` via the plugin + return process.env._next_intl_base_path || ''; + } catch { + return ''; + } +} +function applyPathnamePrefix(pathname, locale, routing, force) { + const { + mode: routingMode + } = routing.localePrefix; + let shouldPrefix; + if (force !== undefined) { + shouldPrefix = force; + } else if (isLocalizableHref(pathname)) { + // Since locales are unique per domain, there should be + // only one domain that contains the locale + const domain = routing.domains?.find(cur => cur.locales.includes(locale)); + + // Domains can override the mode + const mode = domain?.localePrefix || routingMode; + if (mode === 'always') { + shouldPrefix = true; + } else if (mode === 'as-needed') { + shouldPrefix = domain ? locale !== domain.defaultLocale : locale !== routing.defaultLocale; + } + } + return shouldPrefix ? prefixPathname(getLocalePrefix(locale, routing.localePrefix), pathname) : pathname; +} +function validateReceivedConfig(config) { + if (config.localePrefix?.mode === 'as-needed' && !('defaultLocale' in config)) { + throw new Error("`localePrefix: 'as-needed' requires a `defaultLocale`."); + } +} + +export { applyPathnamePrefix, compileLocalizedPathname, getBasePath, getRoute, normalizeNameOrNameWithParams, serializeSearchParams, validateReceivedConfig }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..af4c1ed56f8d7b6dfa924706641dec4f63cbeaa9 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin.js @@ -0,0 +1 @@ +export { default } from './plugin/createNextIntlPlugin.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/config.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/config.js new file mode 100644 index 0000000000000000000000000000000000000000..3560ab3dd6099c9865f01638ea98eb1dc5999670 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/config.js @@ -0,0 +1,10 @@ +// Avoid rollup's `replace` plugin to compile this away +const nodeEnvKey = 'NODE_ENV'.trim(); + +// We avoid reading `argv.includes('dev')` related to +// https://github.com/amannn/next-intl/issues/2006 +const isDevelopment = process.env[nodeEnvKey] === 'development'; +const isNextBuild = process.argv.includes('build'); +const isDevelopmentOrNextBuild = isDevelopment || isNextBuild; + +export { isDevelopment, isDevelopmentOrNextBuild, isNextBuild }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/createNextIntlPlugin.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/createNextIntlPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3571b8db829c77db7abee8e6d1f421a18ddc0c8a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/createNextIntlPlugin.js @@ -0,0 +1,52 @@ +import normalizeExtractorConfig from '../extractor/normalizeExtractorConfig.js'; +import initExtractionCompiler from './extractor/initExtractionCompiler.js'; +import getNextConfig from './getNextConfig.js'; +import { warn } from './utils.js'; +import createMessagesDeclaration from './declaration/createMessagesDeclaration.js'; + +function initPlugin(pluginConfig, nextConfig) { + if (nextConfig?.i18n != null) { + warn("An `i18n` property was found in your Next.js config. This likely causes conflicts and should therefore be removed if you use the App Router.\n\nIf you're in progress of migrating from the Pages Router, you can refer to this example: https://next-intl.dev/examples#app-router-migration\n"); + } + const skipWatchers = isNextTelemetryDetachedFlushProcess(); + const messagesPathOrPaths = pluginConfig.experimental?.createMessagesDeclaration; + if (messagesPathOrPaths && !skipWatchers) { + createMessagesDeclaration(typeof messagesPathOrPaths === 'string' ? [messagesPathOrPaths] : messagesPathOrPaths); + } + let extractorConfig; + const experimental = pluginConfig.experimental; + const extract = experimental?.extract; + if (extract) { + extractorConfig = normalizeExtractorConfig({ + extract, + messages: experimental.messages, + srcPath: experimental.srcPath + }); + } + if (!skipWatchers) { + initExtractionCompiler(extractorConfig); + } + return getNextConfig(pluginConfig, nextConfig, extractorConfig); +} +function createNextIntlPlugin(i18nPathOrConfig = {}) { + const config = typeof i18nPathOrConfig === 'string' ? { + requestConfig: i18nPathOrConfig + } : i18nPathOrConfig; + return function withNextIntl(nextConfig) { + return initPlugin(config, nextConfig); + }; +} + +/** + * Next runs `telemetry/detached-flush.js` in a detached process to flush telemetry + * (often when `next dev` exits). That loads dev `next.config` with inherited + * `NODE_ENV=development`, which would otherwise start orphan plugin watchers. + */ +function isNextTelemetryDetachedFlushProcess() { + const scriptPath = process.argv[1]; + if (!scriptPath) return false; + const normalized = scriptPath.replace(/\\/g, '/'); + return normalized.includes('/telemetry/detached-flush'); +} + +export { createNextIntlPlugin as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/declaration/createMessagesDeclaration.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/declaration/createMessagesDeclaration.js new file mode 100644 index 0000000000000000000000000000000000000000..4bcc41ecebdef46e1eaca665ecfe7a5d57bbf3a6 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/declaration/createMessagesDeclaration.js @@ -0,0 +1,70 @@ +import fs from 'fs'; +import path from 'path'; +import { once, throwError } from '../utils.js'; +import watchFile from '../watchFile.js'; + +const runOnce = once('_NEXT_INTL_COMPILE_MESSAGES'); +function createMessagesDeclaration(messagesPaths) { + // Instead of running _only_ in certain cases, it's + // safer to _avoid_ running for certain known cases. + // https://github.com/amannn/next-intl/issues/2006 + const shouldBailOut = ['info', 'start' + + // Note: These commands don't consult the + // Next.js config, so we can't detect them here. + // - telemetry (however, the `detached-flush` DOES - see `createNextIntlPlugin`) + // - lint + // + // What remains are: + // - dev + // - build + // - typegen + ].some(arg => process.argv.includes(arg)); + if (shouldBailOut) { + return; + } + runOnce(() => { + for (const messagesPath of messagesPaths) { + const fullPath = path.resolve(messagesPath); + if (!fs.existsSync(fullPath)) { + throwError(`\`createMessagesDeclaration\` points to a non-existent file: ${fullPath}`); + } + if (!fullPath.endsWith('.json')) { + throwError(`\`createMessagesDeclaration\` needs to point to a JSON file. Received: ${fullPath}`); + } + + // Keep this as a runtime check and don't replace + // this with a constant during the build process + const env = process.env['NODE_ENV'.trim()]; + compileDeclaration(messagesPath); + if (env === 'development') { + startWatching(messagesPath); + } + } + }); +} +function startWatching(messagesPath) { + const watcher = watchFile(messagesPath, () => { + compileDeclaration(messagesPath, true); + }); + process.on('exit', () => { + watcher.close(); + }); +} +function compileDeclaration(messagesPath, async = false) { + const declarationPath = messagesPath.replace(/\.json$/, '.d.json.ts'); + function createDeclaration(content) { + return `// This file is auto-generated by next-intl, do not edit directly. +// See: https://next-intl.dev/docs/workflows/typescript#messages-arguments + +declare const messages: ${content.trim()}; +export default messages;`; + } + if (async) { + return fs.promises.readFile(messagesPath, 'utf-8').then(content => fs.promises.writeFile(declarationPath, createDeclaration(content))); + } + const content = fs.readFileSync(messagesPath, 'utf-8'); + fs.writeFileSync(declarationPath, createDeclaration(content)); +} + +export { createMessagesDeclaration as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/extractor/initExtractionCompiler.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/extractor/initExtractionCompiler.js new file mode 100644 index 0000000000000000000000000000000000000000..1299ea48de3f801a13733522c048cf0db29be6a4 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/extractor/initExtractionCompiler.js @@ -0,0 +1,54 @@ +import ExtractionCompiler from '../../extractor/ExtractionCompiler.js'; +import { hasLocalesToExtract } from '../../extractor/utils.js'; +import { isDevelopment, isNextBuild } from '../config.js'; +import { once } from '../utils.js'; + +// Single compiler instance, initialized once per process +let compiler; +const runOnce = once('_NEXT_INTL_EXTRACT'); +function initExtractionCompiler(extractorConfig) { + if (!extractorConfig || !hasLocalesToExtract(extractorConfig)) { + return; + } + + // Avoid running for: + // - info + // - start + // - typegen + // + // Doesn't consult Next.js config anyway: + // - lint + // - telemetry (however, the `detached-flush` DOES - see `createNextIntlPlugin`) + // + // What remains are: + // - dev (NODE_ENV=development) + // - build (NODE_ENV=production) + const shouldRun = isDevelopment || isNextBuild; + if (!shouldRun) return; + runOnce(() => { + compiler = new ExtractionCompiler(extractorConfig, { + isDevelopment, + projectRoot: process.cwd() + }); + + // Fire-and-forget: Start extraction, don't block config return. + // In dev mode, this also starts the file watcher. + // In prod, ideally we would wait until the extraction is complete, + // but we can't `await` anywhere (at least for Turbopack). + // The result is ok though, as if we encounter untranslated messages, + // we'll simply add empty messages to the catalog. So for actually + // running the app, there is no difference. + compiler.extractAll(); + function cleanup() { + if (compiler) { + compiler[Symbol.dispose](); + compiler = undefined; + } + } + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + }); +} + +export { initExtractionCompiler as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/getNextConfig.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/getNextConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..1cacf07e38bdfa0e5d89be54d0e6df4d32041f5b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/getNextConfig.js @@ -0,0 +1,281 @@ +import fs from 'fs'; +import { createRequire } from 'module'; +import path from 'path'; +import { getFormatExtension } from '../extractor/format/index.js'; +import { normalizeMessagesCatalogPaths } from '../extractor/normalizeExtractorConfig.js'; +import SourceFileFilter from '../extractor/source/SourceFileFilter.js'; +import { isDevelopmentOrNextBuild } from './config.js'; +import { isNextJs16OrHigher, hasStableTurboConfig } from './nextFlags.js'; +import { throwError } from './utils.js'; + +const require$1 = createRequire(import.meta.url); +function withExtensions(localPath) { + return [`${localPath}.ts`, `${localPath}.tsx`, `${localPath}.js`, `${localPath}.jsx`]; +} +function normalizeTurbopackAliasPath(pathname) { + // Turbopack alias targets should use forward slashes; Windows backslashes can + // break resolution in dev (see `next-intl/config` alias path style). + return pathname.replace(/\\/g, '/'); +} + +/** + * Turbopack validates loader options by comparing them to their JSON round-trip + * (`isDeepStrictEqual(options, JSON.parse(JSON.stringify(options)))`). Since + * `JSON.stringify` drops keys with an `undefined` value, such a key would always + * fail that check, therefore they're removed here. + * https://github.com/amannn/next-intl/issues/2394 + */ +function pruneUndefined(value) { + if (Array.isArray(value)) { + return value.map(pruneUndefined); + } + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined).map(([key, entry]) => [key, pruneUndefined(entry)])); + } + return value; +} +function resolveI18nPath(providedPath, cwd) { + function resolvePath(pathname) { + const parts = []; + if (cwd) parts.push(cwd); + parts.push(pathname); + return path.resolve(...parts); + } + function pathExists(pathname) { + return fs.existsSync(resolvePath(pathname)); + } + if (providedPath) { + // We use the `isNextDevOrBuild` condition to avoid throwing errors + // if `next.config.ts` is read by a non-Next.js process. + // https://github.com/amannn/next-intl/discussions/2209#discussioncomment-15650927 + if (isDevelopmentOrNextBuild && !pathExists(providedPath)) { + throwError(`Could not find i18n config at ${providedPath}, please provide a valid path.`); + } + return providedPath; + } else { + for (const candidate of [...withExtensions('./i18n/request'), ...withExtensions('./src/i18n/request')]) { + if (pathExists(candidate)) { + return candidate; + } + } + if (isDevelopmentOrNextBuild) { + throwError(`Could not locate request configuration module.\n\nThis path is supported by default: ./(src/)i18n/request.{js,jsx,ts,tsx}\n\nAlternatively, you can specify a custom location in your Next.js config:\n\nconst withNextIntl = createNextIntlPlugin(\n './path/to/i18n/request.tsx'\n);`); + } + + // Default as fallback + if (pathExists('./src')) { + return './src/i18n/request.ts'; + } else { + return './i18n/request.ts'; + } + } +} +function getNextConfig(pluginConfig, nextConfig, extractorConfig) { + const useTurbo = process.env.TURBOPACK != null; + + // `experimental-analyze` doesn’t set the TURBOPACK env param. Since Next.js + // 16 doesn't print a warning when we configure both Turbo- and Webpack, just + // always configure Turbopack just in case. + const shouldConfigureTurbo = useTurbo || isNextJs16OrHigher(); + const nextIntlConfig = {}; + let messageLoadPaths = []; + if (pluginConfig.experimental?.messages) { + messageLoadPaths = normalizeMessagesCatalogPaths(pluginConfig.experimental.messages.path); + } + function getExtractMessagesLoaderConfig(config) { + return { + loader: 'next-intl/extractor/extractionLoader', + options: pruneUndefined(config) + }; + } + function getCatalogLoaderConfig() { + const experimental = pluginConfig.experimental; + const messages = experimental.messages; + // Normalization enforces a source locale before extraction runs. + const sourceLocale = messages.sourceLocale ?? (typeof experimental.extract === 'object' ? experimental.extract.sourceLocale : undefined); + return { + loader: 'next-intl/extractor/catalogLoader', + options: pruneUndefined({ + messages: { + format: messages.format, + precompile: messages.precompile, + sourceLocale + } + }) + }; + } + function getTurboRules() { + return nextConfig?.turbopack?.rules || + // @ts-expect-error -- For Next.js <16 + nextConfig?.experimental?.turbo?.rules || {}; + } + function addTurboRule(rules, glob, rule) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (rules[glob]) { + if (Array.isArray(rules[glob])) { + rules[glob].push(rule); + } else { + rules[glob] = [rules[glob], rule]; + } + } else { + rules[glob] = rule; + } + } + if (shouldConfigureTurbo) { + if (pluginConfig.requestConfig && path.isAbsolute(pluginConfig.requestConfig)) { + throwError("Turbopack support for next-intl currently does not support absolute paths, please provide a relative one (e.g. './src/i18n/config.ts').\n\nFound: " + pluginConfig.requestConfig); + } + + // Assign alias for `next-intl/config` + const resolveAlias = { + // Turbo aliases don't work with absolute + // paths (see error handling above) + 'next-intl/config': resolveI18nPath(pluginConfig.requestConfig) + }; + + // Add alias for precompiled message formatting + if (pluginConfig.experimental?.messages?.precompile) { + // Workaround for https://github.com/vercel/next.js/issues/88540 + let formatOnlyPath = path.relative(process.cwd(), require$1.resolve('use-intl/format-message/format-only')); + + // Turbopack seems to require this, otherwise `use-intl/format-message` is + // still bundled (despite the code correctly calling into `format-only`). + // Note that in this monorepo this is not necessary, because we'll end + // up with a path like `../…` — but for actual consumers this is required. + if (!formatOnlyPath.startsWith('.')) { + formatOnlyPath = `./${formatOnlyPath}`; + } + resolveAlias['use-intl/format-message'] = normalizeTurbopackAliasPath(formatOnlyPath); + } + + // Add loaders + let rules; + + // Add loader for extractor + if (pluginConfig.experimental?.extract) { + if (!isNextJs16OrHigher()) { + throwError('Message extraction requires Next.js 16 or higher.'); + } + rules ??= getTurboRules(); + addTurboRule(rules, `*.{${SourceFileFilter.EXTENSIONS.join(',')}}`, { + loaders: [getExtractMessagesLoaderConfig(extractorConfig)], + condition: { + // We don't filter for `path` here to allow transformation + // of `useExtracted` calls in external packages (e.g. monorepos) + content: /(useExtracted|getExtracted)/ + } + }); + } + + // Add loader for catalog + if (pluginConfig.experimental?.messages) { + if (!isNextJs16OrHigher()) { + throwError('Message catalog loading requires Next.js 16 or higher.'); + } + rules ??= getTurboRules(); + const extension = getFormatExtension(pluginConfig.experimental.messages.format); + addTurboRule(rules, `*${extension}`, { + loaders: [getCatalogLoaderConfig()], + condition: { + path: `{${messageLoadPaths.join(',')}}/**/*` + }, + as: '*.js' + }); + } + if (hasStableTurboConfig() && + // @ts-expect-error -- For Next.js <16 + !nextConfig?.experimental?.turbo) { + nextIntlConfig.turbopack = { + ...nextConfig?.turbopack, + ...(rules && { + rules + }), + resolveAlias: { + ...nextConfig?.turbopack?.resolveAlias, + ...resolveAlias + } + }; + } else { + nextIntlConfig.experimental = { + ...nextConfig?.experimental, + // @ts-expect-error -- For Next.js <16 + turbo: { + // @ts-expect-error -- For Next.js <16 + ...nextConfig?.experimental?.turbo, + ...(rules && { + rules + }), + resolveAlias: { + // @ts-expect-error -- For Next.js <16 + ...nextConfig?.experimental?.turbo?.resolveAlias, + ...resolveAlias + } + } + }; + } + } + if (!useTurbo) { + nextIntlConfig.webpack = function webpack(config, context) { + if (!config.resolve) config.resolve = {}; + if (!config.resolve.alias) config.resolve.alias = {}; + + // Assign alias for `next-intl/config` + // (Webpack requires absolute paths) + config.resolve.alias['next-intl/config'] = path.resolve(config.context, resolveI18nPath(pluginConfig.requestConfig, config.context)); + + // Add alias for precompiled message formatting + if (pluginConfig.experimental?.messages?.precompile) { + // Use require.resolve to get the actual file path, since + // bundlers don't properly resolve package subpath exports + // when used as alias targets + config.resolve.alias['use-intl/format-message'] = require$1.resolve('use-intl/format-message/format-only'); + } + + // Add loader for extractor + if (pluginConfig.experimental?.extract) { + if (!config.module) config.module = {}; + if (!config.module.rules) config.module.rules = []; + config.module.rules.push({ + test: new RegExp(`\\.(${SourceFileFilter.EXTENSIONS.join('|')})$`), + use: [getExtractMessagesLoaderConfig(extractorConfig)] + }); + } + + // Add loader for catalog + if (pluginConfig.experimental?.messages) { + if (!config.module) config.module = {}; + if (!config.module.rules) config.module.rules = []; + const extension = getFormatExtension(pluginConfig.experimental.messages.format); + config.module.rules.push({ + test: new RegExp(`${extension.replace(/\./g, '\\.')}$`), + include: messageLoadPaths.map(dirPath => path.resolve(config.context, dirPath)), + use: [getCatalogLoaderConfig()], + type: 'javascript/auto' + }); + } + if (typeof nextConfig?.webpack === 'function') { + return nextConfig.webpack(config, context); + } + return config; + }; + } + + // Forward config + const env = {}; + if (nextConfig?.trailingSlash) { + env._next_intl_trailing_slash = 'true'; + } + if (nextConfig?.basePath) { + env._next_intl_base_path = nextConfig.basePath; + } + // Note that `undefined` values are not supported by Turbopack + if (Object.keys(env).length > 0) { + nextIntlConfig.env = { + ...nextConfig?.env, + ...env + }; + } + return Object.assign({}, nextConfig, nextIntlConfig); +} + +export { getNextConfig as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/nextFlags.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/nextFlags.js new file mode 100644 index 0000000000000000000000000000000000000000..d5f223350ba84e7af7decd3a37c5a7303b9fd42e --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/nextFlags.js @@ -0,0 +1,32 @@ +import { createRequire } from 'module'; + +function getCurrentVersion() { + try { + const require = createRequire(import.meta.url); + const pkg = require('next/package.json'); + return pkg.version; + } catch (error) { + throw new Error('Failed to get current Next.js version. This can happen if next-intl/plugin is imported into your app code outside of your next.config.js.', { + cause: error + }); + } +} +function compareVersions(version1, version2) { + const v1Parts = version1.split('.').map(Number); + const v2Parts = version2.split('.').map(Number); + for (let i = 0; i < 3; i++) { + const v1 = v1Parts[i] || 0; + const v2 = v2Parts[i] || 0; + if (v1 > v2) return 1; + if (v1 < v2) return -1; + } + return 0; +} +function hasStableTurboConfig() { + return compareVersions(getCurrentVersion(), '15.3.0') >= 0; +} +function isNextJs16OrHigher() { + return compareVersions(getCurrentVersion(), '16.0.0') >= 0; +} + +export { hasStableTurboConfig, isNextJs16OrHigher }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/utils.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..b44cb25ba18f79e9e30194e489fe121857986e12 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/utils.js @@ -0,0 +1,26 @@ +function formatMessage(message) { + return `\n[next-intl] ${message}\n`; +} +function throwError(message) { + throw new Error(formatMessage(message)); +} +function warn(message) { + console.warn(formatMessage(message)); +} + +/** + * Returns a function that runs the provided callback only once per process. + * Next.js can call the config multiple times - this ensures we only run once. + * Uses an environment variable to track execution across config loads. + */ +function once(namespace) { + return function runOnce(fn) { + if (process.env[namespace] === '1') { + return; + } + process.env[namespace] = '1'; + fn(); + }; +} + +export { once, throwError, warn }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/plugin/watchFile.js b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/watchFile.js new file mode 100644 index 0000000000000000000000000000000000000000..054566c4927a8894f44a70e2a28b721c79407806 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/plugin/watchFile.js @@ -0,0 +1,21 @@ +import fs from 'fs'; +import path from 'path'; + +/** + * Wrapper around `fs.watch` that provides a workaround + * for https://github.com/nodejs/node/issues/5039. + */ +function watchFile(filepath, callback) { + const directory = path.dirname(filepath); + const filename = path.basename(filepath); + return fs.watch(directory, { + persistent: false, + recursive: false + }, (event, changedFilename) => { + if (changedFilename === filename) { + callback(); + } + }); +} + +export { watchFile as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-client/index.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-client/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1a8524a0fe7c89a131157db2fe225ff4a8db959d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-client/index.js @@ -0,0 +1,34 @@ +import { useFormatter as useFormatter$1, useTranslations as useTranslations$1 } from 'use-intl'; + +/** + * This is the main entry file when non-'react-server' + * environments import from 'next-intl'. + * + * Maintainer notes: + * - Make sure this mirrors the API from 'react-server'. + * - Make sure everything exported from this module is + * supported in all Next.js versions that are supported. + */ + + +// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type +function callHook(name, hook) { + return (...args) => { + try { + return hook(...args); + } catch { + throw new Error(`Failed to call \`${name}\` because the context from \`NextIntlClientProvider\` was not found. + +This can happen because: +1) You intended to render this component as a Server Component, the render + failed, and therefore React attempted to render the component on the client + instead. If this is the case, check the console for server errors. +2) You intended to render this component on the client side, but no context was found. + Learn more about this error here: https://next-intl.dev/docs/environments/server-client-components#missing-context` ); + } + }; +} +const useTranslations = callHook('useTranslations', useTranslations$1); +const useFormatter = callHook('useFormatter', useFormatter$1); + +export { useFormatter, useTranslations }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/NextIntlClientProviderServer.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/NextIntlClientProviderServer.js new file mode 100644 index 0000000000000000000000000000000000000000..1b9c6a13730b50ff8ea1e01c18d65c2724ca2573 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/NextIntlClientProviderServer.js @@ -0,0 +1,34 @@ +import getConfigNow from '../server/react-server/getConfigNow.js'; +import getFormats from '../server/react-server/getFormats.js'; +import NextIntlClientProvider from '../shared/NextIntlClientProvider.js'; +import { jsx } from 'react/jsx-runtime'; +import getTimeZone from '../server/react-server/getTimeZone.js'; +import getMessages from '../server/react-server/getMessages.js'; +import getLocaleCached from '../server/react-server/getLocale.js'; + +async function NextIntlClientProviderServer({ + formats, + locale, + messages, + now, + timeZone, + ...rest +}) { + return /*#__PURE__*/jsx(NextIntlClientProvider + // We need to be careful about potentially reading from headers here. + // See https://github.com/amannn/next-intl/issues/631 + , { + formats: formats === undefined ? await getFormats() : formats, + locale: locale ?? (await getLocaleCached()), + messages: messages === undefined ? await getMessages() : messages + // Note that we don't assign a default for `now` here, + // we only read one from the request config - if any. + // Otherwise this would cause a `dynamicIO` error. + , + now: now ?? (await getConfigNow()), + timeZone: timeZone ?? (await getTimeZone()), + ...rest + }); +} + +export { NextIntlClientProviderServer as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useConfig.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..0e10f8fa97cb5aa3cae9a97007a29669cb4a9da1 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useConfig.js @@ -0,0 +1,21 @@ +import getConfig from '../server/react-server/getConfig.js'; +import use from '../shared/use.js'; + +function useHook(hookName, promise) { + try { + return use(promise); + } catch (error) { + if (error instanceof TypeError && error.message.includes("Cannot read properties of null (reading 'use')")) { + throw new Error(`\`${hookName}\` is not callable within an async component. Please refer to https://next-intl.dev/docs/environments/server-client-components#async-components`, { + cause: error + }); + } else { + throw error; + } + } +} +function useConfig(hookName) { + return useHook(hookName, getConfig()); +} + +export { useConfig as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useExtracted.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useExtracted.js new file mode 100644 index 0000000000000000000000000000000000000000..cf8a07eeffc6ee6c56d7ec998f4d0ceb03357b10 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useExtracted.js @@ -0,0 +1,9 @@ +import getServerExtractor from '../server/react-server/getServerExtractor.js'; +import useConfig from './useConfig.js'; + +function useExtracted(namespace) { + const config = useConfig('useExtracted'); + return getServerExtractor(config, namespace); +} + +export { useExtracted as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useFormatter.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useFormatter.js new file mode 100644 index 0000000000000000000000000000000000000000..cb5dec0d58b3d007089ea117b623bae0ff98131e --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useFormatter.js @@ -0,0 +1,9 @@ +import getFormatterCached from '../server/react-server/getServerFormatter.js'; +import useConfig from './useConfig.js'; + +function useFormatter() { + const config = useConfig('useFormatter'); + return getFormatterCached(config); +} + +export { useFormatter as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useLocale.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..4fb3f1f4426ef0b5dd77d79702895c741509e8f4 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useLocale.js @@ -0,0 +1,8 @@ +import useConfig from './useConfig.js'; + +function useLocale() { + const config = useConfig('useLocale'); + return config.locale; +} + +export { useLocale as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useMessages.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useMessages.js new file mode 100644 index 0000000000000000000000000000000000000000..3f9d5db108001dd4b386eb7fa952ae1f759e0b05 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useMessages.js @@ -0,0 +1,9 @@ +import { getMessagesFromConfig } from '../server/react-server/getMessages.js'; +import useConfig from './useConfig.js'; + +function useMessages() { + const config = useConfig('useMessages'); + return getMessagesFromConfig(config); +} + +export { useMessages as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useNow.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useNow.js new file mode 100644 index 0000000000000000000000000000000000000000..a3a31ffb1716f989ba4784809a7eac74c5c5a0fa --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useNow.js @@ -0,0 +1,12 @@ +import getDefaultNow from '../server/react-server/getDefaultNow.js'; +import useConfig from './useConfig.js'; + +function useNow(options) { + if (options?.updateInterval != null) { + console.error("`useNow` doesn't support the `updateInterval` option in Server Components, the value will be ignored. If you need the value to update, you can convert the component to a Client Component."); + } + const config = useConfig('useNow'); + return config.now ?? getDefaultNow(); +} + +export { useNow as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useTimeZone.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useTimeZone.js new file mode 100644 index 0000000000000000000000000000000000000000..59cc0ca7a7926ec2c9249c95754653f10a82daa8 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useTimeZone.js @@ -0,0 +1,8 @@ +import useConfig from './useConfig.js'; + +function useTimeZone() { + const config = useConfig('useTimeZone'); + return config.timeZone; +} + +export { useTimeZone as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useTranslations.js b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useTranslations.js new file mode 100644 index 0000000000000000000000000000000000000000..b3e58f9bdc375e92b764068c09b3ee04724032aa --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/react-server/useTranslations.js @@ -0,0 +1,9 @@ +import getServerTranslator from '../server/react-server/getServerTranslator.js'; +import useConfig from './useConfig.js'; + +function useTranslations(...[namespace]) { + const config = useConfig('useTranslations'); + return getServerTranslator(config, namespace); +} + +export { useTranslations as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/routing.js b/e-commerce/node_modules/next-intl/dist/esm/development/routing.js new file mode 100644 index 0000000000000000000000000000000000000000..f01a5560c993ec3d7a7eca045cc7a9c823f99bef --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/routing.js @@ -0,0 +1 @@ +export { default as defineRouting } from './routing/defineRouting.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/routing/config.js b/e-commerce/node_modules/next-intl/dist/esm/development/routing/config.js new file mode 100644 index 0000000000000000000000000000000000000000..30f2c0e03cf2c854a3de2ca52a2ff776825cf11c --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/routing/config.js @@ -0,0 +1,26 @@ +function receiveRoutingConfig(input) { + return { + ...input, + localePrefix: receiveLocalePrefixConfig(input.localePrefix), + localeCookie: receiveLocaleCookie(input.localeCookie), + localeDetection: input.localeDetection ?? true, + alternateLinks: input.alternateLinks ?? true + }; +} +function receiveLocaleCookie(localeCookie) { + return localeCookie ?? true ? { + name: 'NEXT_LOCALE', + sameSite: 'lax', + ...(typeof localeCookie === 'object' && localeCookie) + + // `path` needs to be provided based on a detected base path + // that depends on the environment when setting a cookie + } : false; +} +function receiveLocalePrefixConfig(localePrefix) { + return typeof localePrefix === 'object' ? localePrefix : { + mode: localePrefix || 'always' + }; +} + +export { receiveRoutingConfig }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/routing/defineRouting.js b/e-commerce/node_modules/next-intl/dist/esm/development/routing/defineRouting.js new file mode 100644 index 0000000000000000000000000000000000000000..44190d05075cec3b45df7e6851490f4831e8fad2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/routing/defineRouting.js @@ -0,0 +1,25 @@ +function defineRouting(config) { + if (config.domains) { + validateUniqueLocalesPerDomain(config.domains); + } + return config; +} +function validateUniqueLocalesPerDomain(domains) { + const domainsByLocale = new Map(); + for (const { + domain, + locales + } of domains) { + for (const locale of locales) { + const localeDomains = domainsByLocale.get(locale) || new Set(); + localeDomains.add(domain); + domainsByLocale.set(locale, localeDomains); + } + } + const duplicateLocaleMessages = Array.from(domainsByLocale.entries()).filter(([, localeDomains]) => localeDomains.size > 1).map(([locale, localeDomains]) => `- "${locale}" is used by: ${Array.from(localeDomains).join(', ')}`); + if (duplicateLocaleMessages.length > 0) { + console.warn('Locales are expected to be unique per domain, but found overlap:\n' + duplicateLocaleMessages.join('\n') + '\nPlease see https://next-intl.dev/docs/routing/configuration#domains'); + } +} + +export { defineRouting as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server.react-client.js b/e-commerce/node_modules/next-intl/dist/esm/development/server.react-client.js new file mode 100644 index 0000000000000000000000000000000000000000..277a885ef18aa24ccb0de8c511b3ae383076c6d2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server.react-client.js @@ -0,0 +1 @@ +export { getExtracted, getFormatter, getLocale, getMessages, getNow, getRequestConfig, getTimeZone, getTranslations, setRequestLocale } from './server/react-client/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server.react-server.js b/e-commerce/node_modules/next-intl/dist/esm/development/server.react-server.js new file mode 100644 index 0000000000000000000000000000000000000000..149c58d5e754329b79b4c275b53661aad7544bcb --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server.react-server.js @@ -0,0 +1,9 @@ +export { default as getRequestConfig } from './server/react-server/getRequestConfig.js'; +export { default as getFormatter } from './server/react-server/getFormatter.js'; +export { default as getNow } from './server/react-server/getNow.js'; +export { default as getTimeZone } from './server/react-server/getTimeZone.js'; +export { default as getExtracted } from './server/react-server/getExtracted.js'; +export { default as getMessages } from './server/react-server/getMessages.js'; +export { default as getLocale } from './server/react-server/getLocale.js'; +export { default as getTranslations } from './server/react-server/getTranslations.js'; +export { setCachedRequestLocale as setRequestLocale } from './server/react-server/RequestLocaleCache.js'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-client/index.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-client/index.js new file mode 100644 index 0000000000000000000000000000000000000000..31c99280b844be92674dbc3cd5e1b13cde2c5f1f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-client/index.js @@ -0,0 +1,32 @@ +/** + * Allows to import `next-intl/server` in non-RSC environments. + * + * This is mostly relevant for testing, since e.g. a `generateMetadata` + * export from a page might use `next-intl/server`, but the test + * only uses the default export for a page. + */ + +function notSupported(message) { + return () => { + throw new Error(`\`${message}\` is not supported in Client Components.`); + }; +} +function getRequestConfig( +// eslint-disable-next-line @typescript-eslint/no-unused-vars +...args) { + return notSupported('getRequestConfig'); +} +const getFormatter = notSupported('getFormatter'); +const getNow = notSupported('getNow'); +const getTimeZone = notSupported('getTimeZone'); +const getMessages = notSupported('getMessages'); +const getLocale = notSupported('getLocale'); +const getExtracted = notSupported('getExtracted'); + +// The type of `getTranslations` is not assigned here because it +// causes a type error. The types use the `react-server` entry +// anyway, therefore this is irrelevant. +const getTranslations = notSupported('getTranslations'); +const setRequestLocale = notSupported('setRequestLocale'); + +export { getExtracted, getFormatter, getLocale, getMessages, getNow, getRequestConfig, getTimeZone, getTranslations, setRequestLocale }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/RequestLocale.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/RequestLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..8860210b5b44bf2e89eb789406bc863f522884f3 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/RequestLocale.js @@ -0,0 +1,36 @@ +import { headers } from 'next/headers'; +import { cache } from 'react'; +import { HEADER_LOCALE_NAME } from '../../shared/constants.js'; +import { isPromise } from '../../shared/utils.js'; +import { getCachedRequestLocale } from './RequestLocaleCache.js'; + +async function getHeadersImpl() { + const promiseOrValue = headers(); + + // Compatibility with Next.js <15 + return isPromise(promiseOrValue) ? await promiseOrValue : promiseOrValue; +} +const getHeaders = cache(getHeadersImpl); +async function getLocaleFromHeaderImpl() { + let locale; + try { + locale = (await getHeaders()).get(HEADER_LOCALE_NAME) || undefined; + } catch (error) { + if (error instanceof Error && error.digest === 'DYNAMIC_SERVER_USAGE') { + const wrappedError = new Error('Usage of next-intl APIs in Server Components currently opts into dynamic rendering. This limitation will eventually be lifted, but as a stopgap solution, you can use the `setRequestLocale` API to enable static rendering, see https://next-intl.dev/docs/routing/setup#static-rendering', { + cause: error + }); + wrappedError.digest = error.digest; + throw wrappedError; + } else { + throw error; + } + } + return locale; +} +const getLocaleFromHeader = cache(getLocaleFromHeaderImpl); +async function getRequestLocale() { + return getCachedRequestLocale() || (await getLocaleFromHeader()); +} + +export { getRequestLocale }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/RequestLocaleCache.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/RequestLocaleCache.js new file mode 100644 index 0000000000000000000000000000000000000000..0011a743552aec3fea3aa3c99f8d39fa5e5f2bf4 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/RequestLocaleCache.js @@ -0,0 +1,22 @@ +import { cache } from 'react'; + +// See https://github.com/vercel/next.js/discussions/58862 +function getCacheImpl() { + const value = { + locale: undefined + }; + return value; +} +const getCache = cache(getCacheImpl); +function getCachedRequestLocale() { + return getCache().locale; +} + +/** + * @deprecated Please migrate to [`next/root-params`](https://next-intl.dev/blog/nextjs-root-params). + */ +function setCachedRequestLocale(locale) { + getCache().locale = locale; +} + +export { getCachedRequestLocale, setCachedRequestLocale }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/createRequestConfig.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/createRequestConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..8adff7405396ae4ef9cf091caec5429aac80c29b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/createRequestConfig.js @@ -0,0 +1,2 @@ +import getRuntimeConfig from 'next-intl/config'; +export { default } from 'next-intl/config'; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getConfig.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..6e1a9ff70f0efa5a1f311af5eb78d472012d59ad --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getConfig.js @@ -0,0 +1,59 @@ +import { cache } from 'react'; +import { initializeConfig, _createIntlFormatters, _createCache } from 'use-intl/core'; +import { isPromise } from '../../shared/utils.js'; +import { getRequestLocale } from './RequestLocale.js'; +import getRuntimeConfig from 'next-intl/config'; +import validateLocale from './validateLocale.js'; + +// This is automatically inherited by `NextIntlClientProvider` if +// the component is rendered from a Server Component +function getDefaultTimeZoneImpl() { + return Intl.DateTimeFormat().resolvedOptions().timeZone; +} +const getDefaultTimeZone = cache(getDefaultTimeZoneImpl); +async function receiveRuntimeConfigImpl(getConfig, localeOverride) { + if (typeof getConfig !== 'function') { + throw new Error(`Invalid i18n request configuration detected. + +Please verify that: +1. In case you've specified a custom location in your Next.js config, make sure that the path is correct. +2. You have a default export in your i18n request configuration file. + +See also: https://next-intl.dev/docs/usage/configuration#i18n-request +`); + } + const params = { + locale: localeOverride, + // In case the consumer doesn't read `params.locale` and instead provides the + // `locale` (either in a single-language workflow or because the locale is + // read from the user settings), don't attempt to read the request locale. + get requestLocale() { + return localeOverride ? Promise.resolve(localeOverride) : getRequestLocale(); + } + }; + let result = getConfig(params); + if (isPromise(result)) { + result = await result; + } + if (!result.locale) { + throw new Error('No locale was returned from `getRequestConfig`.\n\nSee https://next-intl.dev/docs/usage/configuration#i18n-request'); + } + { + validateLocale(result.locale); + } + return result; +} +const receiveRuntimeConfig = cache(receiveRuntimeConfigImpl); +const getFormatters = cache(_createIntlFormatters); +const getCache = cache(_createCache); +async function getConfigImpl(localeOverride) { + const runtimeConfig = await receiveRuntimeConfig(getRuntimeConfig, localeOverride); + return { + ...initializeConfig(runtimeConfig), + _formatters: getFormatters(getCache()), + timeZone: runtimeConfig.timeZone || getDefaultTimeZone() + }; +} +const getConfig = cache(getConfigImpl); + +export { getConfig as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getConfigNow.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getConfigNow.js new file mode 100644 index 0000000000000000000000000000000000000000..ebc141db133ce5571076a33a9dcc115a996bc8fd --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getConfigNow.js @@ -0,0 +1,10 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; + +async function getConfigNowImpl(locale) { + const config = await getConfig(locale); + return config.now; +} +const getConfigNow = cache(getConfigNowImpl); + +export { getConfigNow as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getDefaultNow.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getDefaultNow.js new file mode 100644 index 0000000000000000000000000000000000000000..cbbe20fd29cc16b19cfe6fc46ec7d76749cabb5c --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getDefaultNow.js @@ -0,0 +1,9 @@ +import { cache } from 'react'; + +function defaultNow() { + // See https://next-intl.dev/docs/usage/dates-times#relative-times-server + return new Date(); +} +const getDefaultNow = cache(defaultNow); + +export { getDefaultNow as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getExtracted.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getExtracted.js new file mode 100644 index 0000000000000000000000000000000000000000..eb91cd25a1617d91380b026453895174d140253a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getExtracted.js @@ -0,0 +1,24 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; +import getServerExtractor from './getServerExtractor.js'; + +// Call signature 1: `getExtracted(namespace)` + +// Call signature 2: `getExtracted({locale, namespace})` + +// Implementation +async function getExtractedImpl(namespaceOrOpts) { + let namespace; + let locale; + if (typeof namespaceOrOpts === 'string') { + namespace = namespaceOrOpts; + } else if (namespaceOrOpts) { + locale = namespaceOrOpts.locale; + namespace = namespaceOrOpts.namespace; + } + const config = await getConfig(locale); + return getServerExtractor(config, namespace); +} +const getExtracted = cache(getExtractedImpl); + +export { getExtracted as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getFormats.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getFormats.js new file mode 100644 index 0000000000000000000000000000000000000000..f8bf811aeb907db490d5799ea9251660e144cb16 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getFormats.js @@ -0,0 +1,10 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; + +async function getFormatsCachedImpl() { + const config = await getConfig(); + return config.formats; +} +const getFormats = cache(getFormatsCachedImpl); + +export { getFormats as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getFormatter.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getFormatter.js new file mode 100644 index 0000000000000000000000000000000000000000..9245402fcf1cb54ee4ee4d37a7b85985b523cc4b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getFormatter.js @@ -0,0 +1,21 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; +import getFormatterCached$1 from './getServerFormatter.js'; + +async function getFormatterCachedImpl(locale) { + const config = await getConfig(locale); + return getFormatterCached$1(config); +} +const getFormatterCached = cache(getFormatterCachedImpl); + +/** + * Returns a formatter based on the given locale. + * + * The formatter automatically receives the request config, but + * you can override it by passing in additional options. + */ +async function getFormatter(opts) { + return getFormatterCached(opts?.locale); +} + +export { getFormatter as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getLocale.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..a5fc97973df7f113daaeb87a640fa780aa9e19bd --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getLocale.js @@ -0,0 +1,10 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; + +async function getLocaleCachedImpl() { + const config = await getConfig(); + return config.locale; +} +const getLocaleCached = cache(getLocaleCachedImpl); + +export { getLocaleCached as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getMessages.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getMessages.js new file mode 100644 index 0000000000000000000000000000000000000000..e7490baa2dcbdbc9b8ee22fed3937b5f528b6cb9 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getMessages.js @@ -0,0 +1,19 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; + +function getMessagesFromConfig(config) { + if (!config.messages) { + throw new Error('No messages found. Have you configured them correctly? See https://next-intl.dev/docs/configuration#messages'); + } + return config.messages; +} +async function getMessagesCachedImpl(locale) { + const config = await getConfig(locale); + return getMessagesFromConfig(config); +} +const getMessagesCached = cache(getMessagesCachedImpl); +async function getMessages(opts) { + return getMessagesCached(opts?.locale); +} + +export { getMessages as default, getMessagesFromConfig }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getNow.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getNow.js new file mode 100644 index 0000000000000000000000000000000000000000..5efbe0bcdad0c9809bae2b135df04669334cd79b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getNow.js @@ -0,0 +1,8 @@ +import getConfigNow from './getConfigNow.js'; +import getDefaultNow from './getDefaultNow.js'; + +async function getNow(opts) { + return (await getConfigNow(opts?.locale)) ?? getDefaultNow(); +} + +export { getNow as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getRequestConfig.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getRequestConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..d33334a3974b0ed570d976d0cd8a9ac290831935 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getRequestConfig.js @@ -0,0 +1,8 @@ +/** + * Should be called in `i18n/request.ts` to create the configuration for the current request. + */ +function getRequestConfig(createRequestConfig) { + return createRequestConfig; +} + +export { getRequestConfig as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerExtractor.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerExtractor.js new file mode 100644 index 0000000000000000000000000000000000000000..9a8d0ccf01bd823eba25a381c62a92dca530aa2b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerExtractor.js @@ -0,0 +1,38 @@ +import { cache } from 'react'; +import getServerTranslator from './getServerTranslator.js'; + +// Note: This API is usually compiled into `useTranslations`, +// but there is some fallback handling which allows this hook +// to still work when not being compiled. +// +// This is relevant for: +// - Isolated environments like tests, Storybook, etc. +// - Fallbacks in case an extracted message is not yet available +function getServerExtractorImpl(config, namespace) { + const t = getServerTranslator(config, namespace); + function translateFn(...[message, values, formats]) { + return t(undefined, values, formats, + // @ts-expect-error -- Secret fallback parameter + message); + } + translateFn.rich = function translateRichFn(...[message, values, formats]) { + return t.rich(undefined, values, formats, + // @ts-expect-error -- Secret fallback parameter + message); + }; + translateFn.markup = function translateMarkupFn(...[message, values, formats]) { + return t.markup(undefined, values, formats, + // @ts-expect-error -- Secret fallback parameter + message); + }; + translateFn.has = function translateHasFn( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + ...[message]) { + // Not really something better we can do here + return true; + }; + return translateFn; +} +var getServerExtractor = cache(getServerExtractorImpl); + +export { getServerExtractor as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerFormatter.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerFormatter.js new file mode 100644 index 0000000000000000000000000000000000000000..e8d2d028aca1f892509c1708a7e8d4440cc43735 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerFormatter.js @@ -0,0 +1,17 @@ +import { cache } from 'react'; +import { createFormatter } from 'use-intl/core'; +import getDefaultNow from './getDefaultNow.js'; + +function getFormatterCachedImpl(config) { + return createFormatter({ + ...config, + // Only init when necessary to avoid triggering a `dynamicIO` error + // unnecessarily (`now` is only needed for `format.relativeTime`) + get now() { + return config.now ?? getDefaultNow(); + } + }); +} +const getFormatterCached = cache(getFormatterCachedImpl); + +export { getFormatterCached as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerTranslator.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerTranslator.js new file mode 100644 index 0000000000000000000000000000000000000000..c29a7676fcd5efe8fc3e99e3a2e9a79734bcd9bf --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getServerTranslator.js @@ -0,0 +1,12 @@ +import { cache } from 'react'; +import { createTranslator } from 'use-intl/core'; + +function getServerTranslatorImpl(config, namespace) { + return createTranslator({ + ...config, + namespace + }); +} +var getServerTranslator = cache(getServerTranslatorImpl); + +export { getServerTranslator as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getTimeZone.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getTimeZone.js new file mode 100644 index 0000000000000000000000000000000000000000..6fe6cfa3416f39f6f6bce276fd7b786b51735c46 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getTimeZone.js @@ -0,0 +1,13 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; + +async function getTimeZoneCachedImpl(locale) { + const config = await getConfig(locale); + return config.timeZone; +} +const getTimeZoneCached = cache(getTimeZoneCachedImpl); +async function getTimeZone(opts) { + return getTimeZoneCached(opts?.locale); +} + +export { getTimeZone as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getTranslations.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getTranslations.js new file mode 100644 index 0000000000000000000000000000000000000000..f393b26888e784e3b4e04d39e0a2a1ebdbc12afd --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/getTranslations.js @@ -0,0 +1,28 @@ +import { cache } from 'react'; +import getConfig from './getConfig.js'; +import getServerTranslator from './getServerTranslator.js'; + +// Maintainer note: `getTranslations` has two different call signatures. +// We need to define these with function overloads, otherwise TypeScript +// messes up the return type. + +// Call signature 1: `getTranslations(namespace)` + +// Call signature 2: `getTranslations({locale, namespace})` + +// Implementation +async function getTranslations(namespaceOrOpts) { + let namespace; + let locale; + if (typeof namespaceOrOpts === 'string') { + namespace = namespaceOrOpts; + } else if (namespaceOrOpts) { + locale = namespaceOrOpts.locale; + namespace = namespaceOrOpts.namespace; + } + const config = await getConfig(locale); + return getServerTranslator(config, namespace); +} +var getTranslations_default = cache(getTranslations); + +export { getTranslations_default as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/validateLocale.js b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/validateLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..8f2b316d83e944516577180c7f6c10c57892b63d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/server/react-server/validateLocale.js @@ -0,0 +1,12 @@ +function validateLocale(locale) { + try { + const constructed = new Intl.Locale(locale); + if (!constructed.language) { + throw new Error('Language is required'); + } + } catch { + console.error(`An invalid locale was provided: "${locale}"\nPlease ensure you're using a valid Unicode locale identifier (e.g. "en-US").`); + } +} + +export { validateLocale as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/shared/NextIntlClientProvider.js b/e-commerce/node_modules/next-intl/dist/esm/development/shared/NextIntlClientProvider.js new file mode 100644 index 0000000000000000000000000000000000000000..65b1dc6ac2b1f794e7a6bd7d6f7718beb9f3f3db --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/shared/NextIntlClientProvider.js @@ -0,0 +1,18 @@ +"use client"; +import { IntlProvider } from 'use-intl/react'; +import { jsx } from 'react/jsx-runtime'; + +function NextIntlClientProvider({ + locale, + ...rest +}) { + if (!locale) { + throw new Error("Couldn't infer the `locale` prop in `NextIntlClientProvider`, please provide it explicitly.\n\nSee https://next-intl.dev/docs/configuration#locale" ); + } + return /*#__PURE__*/jsx(IntlProvider, { + locale: locale, + ...rest + }); +} + +export { NextIntlClientProvider as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/shared/constants.js b/e-commerce/node_modules/next-intl/dist/esm/development/shared/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..41ba9cd7e431195dc98251bfc2c83c04226da24b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/shared/constants.js @@ -0,0 +1,4 @@ +// Used to read the locale from the middleware +const HEADER_LOCALE_NAME = 'X-NEXT-INTL-LOCALE'; + +export { HEADER_LOCALE_NAME }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/shared/use.js b/e-commerce/node_modules/next-intl/dist/esm/development/shared/use.js new file mode 100644 index 0000000000000000000000000000000000000000..afa678a1f541dafd6dab4316cd59bb1cc5189461 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/shared/use.js @@ -0,0 +1,13 @@ +import * as react from 'react'; + +// @ts-expect-error -- Ooof, Next.js doesn't make this easy. +// `use` is only available in React 19 canary, but we can +// use it in Next.js already as Next.js "vendors" a fixed +// version of React. However, if we'd simply put `use` in +// ESM code, then the build doesn't work since React does +// not export `use` officially. Therefore, we have to use +// something that is not statically analyzable. Once React +// 19 is out, we can remove this in the next major version. +var use = react['use'.trim()]; + +export { use as default }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/development/shared/utils.js b/e-commerce/node_modules/next-intl/dist/esm/development/shared/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..e1abe729bf6e5b374e836e5682a6955ee71d68e0 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/development/shared/utils.js @@ -0,0 +1,140 @@ +function isRelativeHref(href) { + const pathname = typeof href === 'object' ? href.pathname : href; + return pathname != null && !pathname.startsWith('/'); +} +function isLocalHref(href) { + if (typeof href === 'object') { + return href.host == null && href.hostname == null; + } else { + const hasProtocol = /^[a-z]+:/i.test(href); + return !hasProtocol; + } +} +function isLocalizableHref(href) { + return isLocalHref(href) && !isRelativeHref(href); +} +function unprefixPathname(pathname, prefix) { + return pathname.replace(new RegExp(`^${prefix}`), '') || '/'; +} +function prefixPathname(prefix, pathname) { + let localizedHref = prefix; + + // Avoid trailing slashes + if (/^\/(\?.*)?$/.test(pathname)) { + pathname = pathname.slice(1); + } + localizedHref += pathname; + return localizedHref; +} +function hasPathnamePrefixed(prefix, pathname) { + return pathname === prefix || pathname.startsWith(`${prefix}/`); +} +function hasTrailingSlash() { + try { + // Provided via `env` setting in `next.config.js` via the plugin + return process.env._next_intl_trailing_slash === 'true'; + } catch { + return false; + } +} +function getLocalizedTemplate(pathnameConfig, locale, internalTemplate) { + return typeof pathnameConfig === 'string' ? pathnameConfig : pathnameConfig[locale] || internalTemplate; +} +function normalizeTrailingSlash(pathname) { + const trailingSlash = hasTrailingSlash(); + const [path, ...hashParts] = pathname.split('#'); + const hash = hashParts.join('#'); + let normalizedPath = path; + if (normalizedPath !== '/') { + const pathnameEndsWithSlash = normalizedPath.endsWith('/'); + if (trailingSlash && !pathnameEndsWithSlash) { + normalizedPath += '/'; + } else if (!trailingSlash && pathnameEndsWithSlash) { + normalizedPath = normalizedPath.slice(0, -1); + } + } + if (hash) { + normalizedPath += '#' + hash; + } + return normalizedPath; +} +function matchesPathname(/** E.g. `/users/[userId]-[userName]` */ +template, /** E.g. `/users/23-jane` */ +pathname) { + const normalizedTemplate = normalizeTrailingSlash(template); + const normalizedPathname = normalizeTrailingSlash(pathname); + const regex = templateToRegex(normalizedTemplate); + return regex.test(normalizedPathname); +} +function getLocalePrefix(locale, localePrefix) { + return localePrefix.mode !== 'never' && localePrefix.prefixes?.[locale] || + // We return a prefix even if `mode: 'never'`. It's up to the consumer + // to decide to use it or not. + getLocaleAsPrefix(locale); +} +function getLocaleAsPrefix(locale) { + return '/' + locale; +} +function templateToRegex(template) { + const regexPattern = template + // Replace optional catchall ('[[...slug]]') + .replace(/\/\[\[(\.\.\.[^\]]+)\]\]/g, '(?:/(.*))?') // With leading slash + .replace(/\[\[(\.\.\.[^\]]+)\]\]/g, '(?:/(.*))?') // Without leading slash + // Replace catchall ('[...slug]') + .replace(/\[(\.\.\.[^\]]+)\]/g, '(.+)') + // Replace regular parameter ('[slug]') + .replace(/\[([^\]]+)\]/g, '([^/]+)'); + return new RegExp(`^${regexPattern}$`); +} +function isOptionalCatchAllSegment(pathname) { + return pathname.includes('[[...'); +} +function isCatchAllSegment(pathname) { + return pathname.includes('[...'); +} +function isDynamicSegment(pathname) { + return pathname.includes('['); +} +function comparePathnamePairs(a, b) { + const pathA = a.split('/'); + const pathB = b.split('/'); + const maxLength = Math.max(pathA.length, pathB.length); + for (let i = 0; i < maxLength; i++) { + const segmentA = pathA[i]; + const segmentB = pathB[i]; + + // If one of the paths ends, prioritize the shorter path + if (!segmentA && segmentB) return -1; + if (segmentA && !segmentB) return 1; + if (!segmentA && !segmentB) continue; + + // Prioritize static segments over dynamic segments + if (!isDynamicSegment(segmentA) && isDynamicSegment(segmentB)) return -1; + if (isDynamicSegment(segmentA) && !isDynamicSegment(segmentB)) return 1; + + // Prioritize non-catch-all segments over catch-all segments + if (!isCatchAllSegment(segmentA) && isCatchAllSegment(segmentB)) return -1; + if (isCatchAllSegment(segmentA) && !isCatchAllSegment(segmentB)) return 1; + + // Prioritize non-optional catch-all segments over optional catch-all segments + if (!isOptionalCatchAllSegment(segmentA) && isOptionalCatchAllSegment(segmentB)) { + return -1; + } + if (isOptionalCatchAllSegment(segmentA) && !isOptionalCatchAllSegment(segmentB)) { + return 1; + } + if (segmentA === segmentB) continue; + } + + // Both pathnames are completely static + return 0; +} +function getSortedPathnames(pathnames) { + return pathnames.sort(comparePathnamePairs); +} +function isPromise(value) { + // https://github.com/amannn/next-intl/issues/1711 + return typeof value.then === 'function'; +} + +export { getLocaleAsPrefix, getLocalePrefix, getLocalizedTemplate, getSortedPathnames, hasPathnamePrefixed, isLocalizableHref, isPromise, matchesPathname, normalizeTrailingSlash, prefixPathname, templateToRegex, unprefixPathname }; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/config.js b/e-commerce/node_modules/next-intl/dist/esm/production/config.js new file mode 100644 index 0000000000000000000000000000000000000000..72059d4bbb51e952ce6152b20186ccd5bccd8a94 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/config.js @@ -0,0 +1 @@ +function t(){throw new Error("Couldn't find next-intl config file. Please follow the instructions at https://next-intl.dev/docs/getting-started/app-router")}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor.js new file mode 100644 index 0000000000000000000000000000000000000000..cc942c9a16764bca48173d9b0ab47cd8defedab5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor.js @@ -0,0 +1 @@ +export{default as unstable_extractMessages}from"./extractor/extractMessages.js";export{defineCodec}from"./extractor/format/ExtractorCodec.js"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/ExtractionCompiler.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/ExtractionCompiler.js new file mode 100644 index 0000000000000000000000000000000000000000..24aa5d8ac1957eca13f69abac356852cdd4f710a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/ExtractionCompiler.js @@ -0,0 +1 @@ +import s from"./catalog/CatalogManager.js";import t from"./extractor/MessageExtractor.js";class o{constructor(o,a={}){const e=a.extractor??new t(a);this.manager=new s(o,{...a,extractor:e}),this[Symbol.dispose]=this[Symbol.dispose].bind(this),this.installExitHandlers()}async extractAll(){await this.manager.loadMessages(),await this.manager.save()}[Symbol.dispose](){this.uninstallExitHandlers(),this.manager[Symbol.dispose]()}installExitHandlers(){const s=this[Symbol.dispose];process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}uninstallExitHandlers(){const s=this[Symbol.dispose];process.off("exit",s),process.off("SIGINT",s),process.off("SIGTERM",s)}}export{o as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogLocales.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogLocales.js new file mode 100644 index 0000000000000000000000000000000000000000..3a1fb5a2df63a2512eafc266043815b740120388 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogLocales.js @@ -0,0 +1 @@ +import e from"fs";import s from"fs/promises";import t from"path";class a{onChangeCallbacks=new Set;constructor(e){this.messagesDir=e.messagesDir,this.sourceLocale=e.sourceLocale,this.extension=e.extension,this.locales=e.locales}async getTargetLocales(){return this.targetLocales||("infer"===this.locales?this.targetLocales=await this.readTargetLocales():this.targetLocales=this.locales.filter((e=>e!==this.sourceLocale))),this.targetLocales}async readTargetLocales(){try{return(await s.readdir(this.messagesDir)).filter((e=>e.endsWith(this.extension))).map((e=>t.basename(e,this.extension))).filter((e=>e!==this.sourceLocale))}catch{return[]}}subscribeLocalesChange(e){this.onChangeCallbacks.add(e),"infer"!==this.locales||this.watcher||this.startWatcher()}unsubscribeLocalesChange(e){this.onChangeCallbacks.delete(e),0===this.onChangeCallbacks.size&&this.stopWatcher()}async startWatcher(){this.watcher||(await s.mkdir(this.messagesDir,{recursive:!0}),this.watcher=e.watch(this.messagesDir,{persistent:!1,recursive:!1},((e,s)=>{null!=s&&s.endsWith(this.extension)&&!s.includes(t.sep)&&this.onChange()})))}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=void 0)}async onChange(){const e=new Set(this.targetLocales||[]);this.targetLocales=await this.readTargetLocales();const s=new Set(this.targetLocales),t=this.targetLocales.filter((s=>!e.has(s))),a=Array.from(e).filter((e=>!s.has(e)));if(t.length>0||a.length>0)for(const e of this.onChangeCallbacks)e({added:t,removed:a})}}export{a as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogManager.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogManager.js new file mode 100644 index 0000000000000000000000000000000000000000..cf94137ca94eadb854913d68ccbcbdd6f06ce0b7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogManager.js @@ -0,0 +1 @@ +import e from"fs/promises";import s from"path";import{resolveCodec as t,getFormatExtension as a}from"../format/index.js";import o from"../source/SourceFileScanner.js";import r from"../source/SourceFileWatcher.js";import{getDefaultProjectRoot as i,localeCompare as c,compareReferences as n}from"../utils.js";import l from"./CatalogLocales.js";import h from"./CatalogPersister.js";import g from"./SaveScheduler.js";class d{static extractorOwnedAggregatorKeys=new Set(["description","id","message","references"]);sourceMessagesByFile=new Map;sourceMessagesById=new Map;messagesById=new Map;translationsByTargetLocale=new Map;lastWriteByLocale=new Map;constructor(e,s){this.config=e,this.saveScheduler=new g(s.saveDebounceMs??50),this.projectRoot=s.projectRoot??i(),this.isDevelopment=s.isDevelopment??!1,this.extractor=s.extractor,this.isDevelopment&&(this.sourceWatcher=new r(this.getSrcPaths(),this.handleFileEvents.bind(this)),this.sourceWatcher.start())}async getCodec(){return this.codec||(this.codec=await t(this.config.messages.format,this.projectRoot)),this.codec}async getPersister(){return this.persister||(this.persister=new h({messagesPath:this.config.extract.path,codec:await this.getCodec(),extension:a(this.config.messages.format),sourceLocale:this.config.extract.sourceLocale})),this.persister}getCatalogLocales(){if(this.catalogLocales)return this.catalogLocales;{const e=s.join(this.projectRoot,this.config.extract.path);return this.catalogLocales=new l({messagesDir:e,extension:a(this.config.messages.format),locales:this.config.extract.locales,sourceLocale:this.config.extract.sourceLocale}),this.catalogLocales}}async getTargetLocales(){return this.getCatalogLocales().getTargetLocales()}getSrcPaths(){return(Array.isArray(this.config.extract.srcPath)?this.config.extract.srcPath:[this.config.extract.srcPath]).map((e=>s.join(this.projectRoot,e)))}async loadMessages(){const e=await this.loadSourceMessages();if(this.loadCatalogsPromise=this.loadTargetMessages(),await this.loadCatalogsPromise,this.scanCompletePromise=(async()=>{const s=Array.from(await o.getSourceFiles(this.getSrcPaths())).toSorted(c),t=await Promise.all(s.map((async e=>({filePath:e,messages:await this.extractFile(e)}))));for(const{filePath:e,messages:s}of t)s&&this.applyFileMessages(e,s);this.mergeSourceDiskMetadata(e)})(),await this.scanCompletePromise,this.isDevelopment){this.getCatalogLocales().subscribeLocalesChange(this.onLocalesChange)}}async loadSourceMessages(){const e=await this.loadLocaleMessages(this.config.extract.sourceLocale),s=new Map;for(const t of e)s.set(t.id,t);return s}async loadLocaleMessages(e){const s=await this.getPersister(),t=await s.read(e),a=await s.getLastModified(e);return this.lastWriteByLocale.set(e,a),t}async loadTargetMessages(){const e=await this.getTargetLocales();await Promise.all(e.map((e=>this.reloadLocaleCatalog(e))))}async reloadLocaleCatalog(e){const s=await this.loadLocaleMessages(e);if(e===this.config.extract.sourceLocale)for(const e of s){const s=this.messagesById.get(e.id);if(s)for(const t of Object.keys(e))d.extractorOwnedAggregatorKeys.has(t)||(s[t]=e[t])}else{const t=this.translationsByTargetLocale.get(e),a=t&&t.size>0;if(s.length>0){const t=new Map;for(const e of s)t.set(e.id,e);this.translationsByTargetLocale.set(e,t)}else if(a);else{const s=new Map;this.translationsByTargetLocale.set(e,s)}}}mergeSourceDiskMetadata(e){for(const[s,t]of e){const e=this.messagesById.get(s);if(e)for(const s of Object.keys(t))d.extractorOwnedAggregatorKeys.has(s)||null!=e[s]||(e[s]=t[s])}}async processFile(e){const s=await this.extractFile(e);return!!s&&this.applyFileMessages(e,s)}async extractFile(s){let t=[];try{const a=await e.readFile(s,"utf8");let o;try{o=await this.extractor.extract(s,a)}catch{return}t=o.messages}catch(e){if("ENOENT"!==e.code)throw e}return t}applyFileMessages(e,s){const t=this.sourceMessagesByFile.get(e),a=this.groupSourceMessagesById(s),o=new Set([...t?.keys()??[],...a.keys()]);a.size>0?this.sourceMessagesByFile.set(e,a):this.sourceMessagesByFile.delete(e);for(const s of o){const t=this.sourceMessagesById.get(s);t&&(t.delete(e),0===t.size&&this.sourceMessagesById.delete(s));const o=a.get(s);if(o){let t=this.sourceMessagesById.get(s);t||(t=new Map,this.sourceMessagesById.set(s,t)),t.set(e,o)}this.rebuildMessageById(s)}return this.haveMessagesChangedForFile(t,a)}groupSourceMessagesById(e){const s=new Map;for(const t of e){const e=s.get(t.id);e?e.push(t):s.set(t.id,[t])}return s}rebuildMessageById(e){const s=Array.from(this.sourceMessagesById.get(e)?.values()??[]).flat();if(0===s.length)return void this.messagesById.delete(e);const t=this.messagesById.get(e),a={description:this.mergeDescriptions(s),id:e,message:s[0].message,references:s.map((e=>e.reference)).sort(n)};if(t)for(const e of Object.keys(t))d.extractorOwnedAggregatorKeys.has(e)||null!=a[e]||(a[e]=t[e]);this.messagesById.set(e,a)}mergeDescriptions(e){const s=e.toSorted(((e,s)=>n(e.reference,s.reference))),t=[];for(const e of s){const{description:s}=e;null==s||t.includes(s)||t.push(s)}return t}haveMessagesChangedForFile(e,s){if(!e)return s.size>0;if(e.size!==s.size)return!0;for(const[t,a]of e){const e=s.get(t);if(!e)return!0;if(!this.areSourceMessageArraysEqual(a,e))return!0}return!1}areSourceMessageArraysEqual(e,s){return e.length===s.length&&e.every(((e,t)=>this.areSourceMessagesEqual(e,s[t])))}areSourceMessagesEqual(e,s){return e.id===s.id&&e.message===s.message&&e.description===s.description&&e.reference.path===s.reference.path&&e.reference.line===s.reference.line&&e.reference.column===s.reference.column}async save(){return this.saveScheduler.schedule((()=>this.saveImpl()))}async saveImpl(){await this.saveLocale(this.config.extract.sourceLocale);const e=await this.getTargetLocales();await Promise.all(e.map((e=>this.saveLocale(e))))}async saveLocale(e){await this.loadCatalogsPromise;const s=Array.from(this.messagesById.values()),t=await this.getPersister(),a=e===this.config.extract.sourceLocale,o=this.lastWriteByLocale.get(e),r=await t.getLastModified(e);r&&o&&r>o&&await this.reloadLocaleCatalog(e);const i=a?this.messagesById:this.translationsByTargetLocale.get(e),c=s.map((e=>{const s=i?.get(e.id);return{...s,id:e.id,description:e.description,references:e.references,message:a?e.message:s?.message??""}}));await t.write(c,{locale:e,sourceMessagesById:this.messagesById});const n=await t.getLastModified(e);this.lastWriteByLocale.set(e,n)}onLocalesChange=async e=>{this.loadCatalogsPromise=Promise.all([this.loadCatalogsPromise,...e.added.map((e=>this.reloadLocaleCatalog(e)))]);for(const s of e.added)await this.saveLocale(s);for(const s of e.removed)this.translationsByTargetLocale.delete(s),this.lastWriteByLocale.delete(s)};async handleFileEvents(e){this.loadCatalogsPromise&&await this.loadCatalogsPromise,this.scanCompletePromise&&await this.scanCompletePromise;let s=!1;const t=await this.sourceWatcher.expandDirectoryDeleteEvents(e,Array.from(this.sourceMessagesByFile.keys()));for(const e of t.toSorted(((e,s)=>c(e.path,s.path)))){const t=await this.processFile(e.path);s||=t}s&&await this.save()}[Symbol.dispose](){this.sourceWatcher?.stop(),this.sourceWatcher=void 0,this.saveScheduler[Symbol.dispose](),this.catalogLocales&&this.isDevelopment&&this.catalogLocales.unsubscribeLocalesChange(this.onLocalesChange)}}export{d as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogPersister.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogPersister.js new file mode 100644 index 0000000000000000000000000000000000000000..b238b025db2ceaa0dd63288d6ff1859d2d3f37f5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/CatalogPersister.js @@ -0,0 +1 @@ +import e from"fs/promises";import t from"path";import{warnAboutMissingReferences as s}from"../utils.js";class r{constructor(e){this.messagesPath=e.messagesPath,this.codec=e.codec,this.extension=e.extension,this.sourceLocale=e.sourceLocale}getFileName(e){return e+this.extension}getFilePath(e){return t.join(this.messagesPath,this.getFileName(e))}async read(t){const s=this.getFilePath(t);let r;try{r=await e.readFile(s,"utf8")}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return[];throw new Error(`Error while reading ${this.getFileName(t)}:\n> ${e}`,{cause:e})}try{const e=this.codec.decode(r,{locale:t,sourceLocale:this.sourceLocale});return function(e){for(const t of e){const e=t.segments;if(!Array.isArray(e))continue;const s=e.findIndex((e=>"number"==typeof e));if(-1===s)continue;const r=e.slice(0,s).join(".");throw new Error(`Message at \`${r}\` resolved to an array, but only strings are supported. See https://next-intl.dev/docs/usage/translations#arrays-of-messages`)}}(e),e}catch(e){throw new Error(`Error while decoding ${this.getFileName(t)}:\n> ${e}`,{cause:e})}}async write(r,o){const i=this.getFilePath(o.locale);s(r);const a=this.codec.encode(r,o);try{const s=t.dirname(i);await e.mkdir(s,{recursive:!0}),await e.writeFile(i,a)}catch(e){console.error(`❌ Failed to write catalog: ${e}`)}}async getLastModified(t){const s=this.getFilePath(t);try{return(await e.stat(s)).mtime}catch{return}}}export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/SaveScheduler.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/SaveScheduler.js new file mode 100644 index 0000000000000000000000000000000000000000..b713ba5d307a7df1180595b6b9379f2502cb5abf --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalog/SaveScheduler.js @@ -0,0 +1 @@ +class e{isSaving=!1;pendingResolvers=[];constructor(e=50){this.delayMs=e}async schedule(e){return new Promise(((s,i)=>{this.pendingResolvers.push({resolve:s,reject:i}),this.nextSaveTask=e,this.isSaving||this.saveTimeout?this.saveTimeout&&this.scheduleSave():this.executeSave()}))}scheduleSave(){this.saveTimeout&&clearTimeout(this.saveTimeout),this.saveTimeout=setTimeout((()=>{this.saveTimeout=void 0,this.executeSave()}),this.delayMs)}async executeSave(){if(this.isSaving)return;const e=this.nextSaveTask;if(!e)return;const s=this.pendingResolvers;this.pendingResolvers=[],this.nextSaveTask=void 0,this.isSaving=!0;try{const i=await e();s.forEach((({resolve:e})=>e(i)))}catch(e){s.forEach((({reject:s})=>s(e)))}finally{this.isSaving=!1,this.pendingResolvers.length>0&&this.scheduleSave()}}[Symbol.dispose](){this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=void 0),this.pendingResolvers=[],this.nextSaveTask=void 0,this.isSaving=!1}}export{e as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalogLoader.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalogLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..7b4b04a0c326b3a58fcabeeb386640deec7e7c20 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/catalogLoader.js @@ -0,0 +1 @@ +import e from"path";import t from"icu-minify/compile";import{getFormatExtension as s,resolveCodec as o}from"./format/index.js";import{setNestedProperty as r}from"./utils.js";let n=null,a=!1;const i=new Map;function c(c){const u=this.getOptions(),f=this.async(),d=s(u.messages.format);(async function(e,t){return n||(n=await o(e.messages.format,t)),n})(u,this.rootContext).then((s=>{!function(e){if(a||!e.toJSONString)return;a=!0,console.warn("`toJSONString` is deprecated and no longer needed, please remove it.")}(s);const o=e.basename(this.resourcePath,d),n=s.decode(c,{locale:o,sourceLocale:u.messages.sourceLocale});let m;if(u.messages.precompile){m=function(e,s){const o=Object.create(null),n=new Set(s.keys());for(const a of e){n.delete(a.id),l(a);const e=a.message,i=s.get(a.id);let c;i?.messageValue===e?c=i.compiledMessage:(c=t(e),s.set(a.id,{compiledMessage:c,messageValue:e})),r(o,a.id,c)}for(const e of n)s.delete(e);return o}(n,function(e){let t=i.get(e);return t||(t=new Map,i.set(e,t)),t}(this.resourcePath))}else m=function(e){const t=Object.create(null);for(const s of e)l(s),r(t,s.id,s.message);return t}(n);const g=`export default JSON.parse(${JSON.stringify(JSON.stringify(m))});`;f(null,g)})).catch(f)}function l(e){const t=e.message;if(Array.isArray(t))throw new Error(`Message at \`${e.id}\` resolved to an array, but only strings are supported. See https://next-intl.dev/docs/usage/translations#arrays-of-messages`);if("object"==typeof t)throw new Error(`Message at \`${e.id}\` resolved to \`${typeof t}\`, but only strings are supported. Use a \`.\` to retrieve nested messages. See https://next-intl.dev/docs/usage/translations#structuring-messages`)}export{c as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractMessages.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractMessages.js new file mode 100644 index 0000000000000000000000000000000000000000..bd1f55fa96343f449708b9b2b82ae9b603caf6bb --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractMessages.js @@ -0,0 +1 @@ +import{warn as t}from"../plugin/utils.js";import o from"./ExtractionCompiler.js";import r from"./extractor/MessageExtractor.js";import e from"./normalizeExtractorConfig.js";import{hasLocalesToExtract as s,getDefaultProjectRoot as i}from"./utils.js";async function a(a){const m=e(a);if(!s(m))return void t("`messages.locales` is empty, so no messages were updated.");const n=new o(m,{extractor:new r({isDevelopment:!1,projectRoot:i()})});await n.extractAll()}export{a as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractionLoader.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractionLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..c18e552b268e3facbdb01aa834a284f54484738f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractionLoader.js @@ -0,0 +1 @@ +import t from"./extractor/MessageExtractor.js";let e;function o(o){const r=this.async(),s=this.rootContext,a="development"===process.env["NODE_ENV".trim()];e||(e=new t({isDevelopment:a,projectRoot:s,sourceMap:this.sourceMap})),e.extract(this.resourcePath,o).then((t=>{r(null,t.code,t.map?JSON.parse(t.map):void 0)})).catch(r)}export{o as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractor/LRUCache.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractor/LRUCache.js new file mode 100644 index 0000000000000000000000000000000000000000..eff893bd96daaeb6ab16a8c2c198ac1e40068bcc --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractor/LRUCache.js @@ -0,0 +1 @@ +class e{constructor(e){this.maxSize=e,this.cache=new Map}set(e,t){if(!this.cache.has(e)&&this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,{key:e,value:t})}get(e){const t=this.cache.get(e);if(t)return this.cache.delete(e),this.cache.set(e,t),t.value}}export{e as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractor/MessageExtractor.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractor/MessageExtractor.js new file mode 100644 index 0000000000000000000000000000000000000000..022333f9849cf863ebff5ea01a584ec8be9d8716 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/extractor/MessageExtractor.js @@ -0,0 +1 @@ +import{createRequire as e}from"module";import t from"path";import{transform as s}from"@swc/core";import{getDefaultProjectRoot as r,normalizePathToPosix as o}from"../utils.js";import i from"./LRUCache.js";const c=e(import.meta.url);class a{compileCache=new i(750);constructor(e){this.isDevelopment=e.isDevelopment??!1,this.projectRoot=e.projectRoot??r(),this.sourceMap=e.sourceMap??!1}async extract(e,r){const i=[r,e].join("!"),a=this.compileCache.get(i);if(a)return a;if(!r.includes("useExtracted")&&!r.includes("getExtracted"))return{messages:[],code:r};const p=o(t.relative(this.projectRoot,e)),n=await s(r,{jsc:{target:"esnext",parser:{syntax:"typescript",tsx:!0,decorators:!0},experimental:{cacheRoot:"node_modules/.cache/swc",disableBuiltinTransformsForInternalTesting:!0,disableAllLints:!0,plugins:[[c.resolve("next-intl-swc-plugin-extractor"),{isDevelopment:this.isDevelopment,filePath:p}]]}},sourceMaps:this.sourceMap,sourceFileName:e,filename:p}),l=n.output,m=JSON.parse(JSON.parse(l).results).filter((e=>"extracted"===e.type)).map((e=>({id:e.id,message:e.message,description:e.description,reference:e.reference}))),u={code:n.code,map:n.map,messages:m};return this.compileCache.set(i,u),u}}export{a as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/ExtractorCodec.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/ExtractorCodec.js new file mode 100644 index 0000000000000000000000000000000000000000..a2bc3b65f528ae36f70232918f8fca34101f8eaf --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/ExtractorCodec.js @@ -0,0 +1 @@ +function n(n){return n}export{n as defineCodec}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/codecs/BuiltInPoCodec.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/codecs/BuiltInPoCodec.js new file mode 100644 index 0000000000000000000000000000000000000000..477b38121da63055a89b4784281f66677d23d702 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/codecs/BuiltInPoCodec.js @@ -0,0 +1 @@ +import e from"@eloqnt/format-po";import{defineCodec as t}from"../ExtractorCodec.js";var o=t((()=>{const t=e();return{...t,decode:(e,o)=>(function(e){if(e.includes("X-Crowdin-SourceKey: msgstr"))throw new Error("This catalog uses the previous PO layout of next-intl, which stored message keys in `msgid`. The PO format now follows the gettext convention: the source text in `msgid` and the message key in `msgctxt`. Please migrate your catalogs, or use a custom codec to keep the previous layout: https://github.com/amannn/next-intl/pull/2393")}(e),t.decode(e,o))}}));export{o as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/index.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b87d93c685d595c5f101c21d9ea1bdc04c9655bd --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/format/index.js @@ -0,0 +1 @@ +import{createRequire as o}from"module";import e from"path";import{pathToFileURL as t}from"url";import{throwError as n}from"../../plugin/utils.js";const c={json:{codec:()=>import("@eloqnt/format-json"),extension:".json"},po:{codec:()=>import("./codecs/BuiltInPoCodec.js"),extension:".po"}};function r(o){return"string"==typeof o&&o in c}function i(o){return r(o)?c[o].extension:o.extension}async function s(i,s){if(r(i)){return(0,(await c[i].codec()).default)()}{let c,r;if(i.codec.startsWith(".")||e.isAbsolute(i.codec))c=e.resolve(s,i.codec);else try{c=o(e.join(s,"noop.js")).resolve(i.codec)}catch(o){n(`Could not resolve the codec package "${i.codec}". Is it installed?\n${o}`)}try{r=await import(t(c).href)}catch(o){n(`Could not load codec from "${c}".\n${o}`)}const d=r.default;return d&&"function"==typeof d||n(`Codec at "${c}" must have a default export returned from \`defineCodec\`.`),d()}}export{c as default,i as getFormatExtension,s as resolveCodec}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/normalizeExtractorConfig.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/normalizeExtractorConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..6900042f98d88fe66e04a1e1f31309f1f17bc638 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/normalizeExtractorConfig.js @@ -0,0 +1 @@ +import{throwError as e,warn as s}from"../plugin/utils.js";function a(e){return e.endsWith("/")?e.slice(0,-1):e}function t(e){return(Array.isArray(e)?e:[e]).map((e=>a(String(e).trim()))).filter((e=>e.length>0))}function r(r){null==r.messages&&e("`messages` is required when extracting messages.");const c=r.extract;let o,i;void 0!==c&&!0!==c&&(c.sourceLocale&&(s("`extract.sourceLocale` is deprecated in favor of `messages.sourceLocale`."),i=c.sourceLocale),c.path&&(o=a(c.path)));const n=r.messages.locales;n||e("`messages.locales` is required when extracting messages."),r.messages.sourceLocale&&(i=r.messages.sourceLocale),i||e("`messages.sourceLocale` is required when extracting messages.");const l=r.srcPath;null==l&&e("`srcPath` is required when extracting messages.");const g=Array.isArray(r.messages.path),m=t(r.messages.path);return 0===m.length&&e("`messages.path` must not be empty."),null==o&&(g&&e("When `messages.path` is an array, `extract.path` is required to select the writable catalog directory."),o=m[0]),{extract:{locales:n,path:o,sourceLocale:i,srcPath:l},messages:{format:r.messages.format,path:m}}}export{r as default,t as normalizeMessagesCatalogPaths}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileFilter.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileFilter.js new file mode 100644 index 0000000000000000000000000000000000000000..a913f4251ba2331135035632ebdad8265a70112e --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileFilter.js @@ -0,0 +1 @@ +import t from"path";class i{static EXTENSIONS=["ts","tsx","js","jsx"];static IGNORED_DIRECTORIES=["node_modules",".next",".git"];static isSourceFile(s){const e=t.extname(s);return i.EXTENSIONS.map((t=>"."+t)).includes(e)}static shouldEnterDirectory(s,e){const r=t.basename(s);return!i.IGNORED_DIRECTORIES.includes(r)||i.isIgnoredDirectoryExplicitlyIncluded(s,e)}static isIgnoredDirectoryExplicitlyIncluded(t,s){return s.some((s=>i.isWithinPath(s,t)))}static isWithinPath(i,s){const e=t.relative(s,i);return""===e||!e.startsWith("..")}}export{i as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileScanner.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileScanner.js new file mode 100644 index 0000000000000000000000000000000000000000..e0057e2004a117609649b25e43d9f2bbf6ffe74b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileScanner.js @@ -0,0 +1 @@ +import e from"fs/promises";import i from"path";import r from"./SourceFileFilter.js";class t{static async walkSourceFiles(o,s,a=[]){const c=await e.readdir(o,{withFileTypes:!0});for(const e of c){const c=i.join(o,e.name);if(e.isDirectory()){if(!r.shouldEnterDirectory(c,s))continue;await t.walkSourceFiles(c,s,a)}else r.isSourceFile(e.name)&&a.push(c)}return a}static async getSourceFiles(e){const i=(await Promise.all(e.map((i=>t.walkSourceFiles(i,e))))).flat();return new Set(i)}}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileWatcher.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileWatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..a3e1597ff3fe9a514dfee789cf173b78e0021631 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/source/SourceFileWatcher.js @@ -0,0 +1 @@ +import t from"fs/promises";import s from"path";import{subscribe as e}from"@parcel/watcher";import o from"./SourceFileFilter.js";import r from"./SourceFileScanner.js";class i{subscriptions=[];constructor(t,s){this.roots=t,this.onChange=s}async start(){if(this.subscriptions.length>0)return;const t=o.IGNORED_DIRECTORIES.map((t=>`**/${t}/**`));for(const s of this.roots){const o=await e(s,(async(t,s)=>{if(t)return void console.error(t);const e=await this.normalizeEvents(s);e.length>0&&await this.onChange(e)}),{ignore:t});this.subscriptions.push(o)}}async normalizeEvents(s){const e=[],i=[];await Promise.all(s.map((async s=>{if("create"===s.type)try{if((await t.stat(s.path)).isDirectory())return void e.push(s.path)}catch{}i.push(s)})));let a=[];if(e.length>0)try{const t=await r.getSourceFiles(e);a=Array.from(t).map((t=>({type:"create",path:t})))}catch{}const n=[...i,...a],c=new Set,p=[];for(const t of n){const s=`${t.type}:${t.path}`;c.has(s)||(c.add(s),p.push(t))}return p.filter((t=>"delete"===t.type||o.isSourceFile(t.path)))}async expandDirectoryDeleteEvents(t,e){const r=[];for(const i of t)if("delete"!==i.type||o.isSourceFile(i.path))r.push(i);else{const t=s.resolve(i.path),a=[];for(const s of e)o.isWithinPath(s,t)&&a.push(s);if(a.length>0)for(const t of a)r.push({type:"delete",path:t});else r.push(i)}return r}async stop(){await Promise.all(this.subscriptions.map((t=>t.unsubscribe()))),this.subscriptions=[]}[Symbol.dispose](){this.stop()}}export{i as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/extractor/utils.js b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..725f8dbb08fe3306ac390d13dcae7a8eb4fcc6bc --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/extractor/utils.js @@ -0,0 +1 @@ +import t from"path";import{warn as n}from"../plugin/utils.js";function e(n){return t.posix.normalize(n.split(t.win32.sep).join(t.posix.sep))}const o=new Set(["__proto__","constructor","prototype"]);function r(t){return o.has(t)}function c(t){const{locales:n}=t.extract;return"infer"===n||n.length>0}function i(t,n,e){const o=n.split(".");for(const t of o)if(r(t))throw new Error(`Invalid message id segment: ${t}`);let c=t;for(let t=0;t; rel="alternate"; hreflang="${t}"`}function d(e,a){if(i&&"object"==typeof i){const t=i[c];return l(e,t??s,i[a]??s)}return e}h&&(f.port="",f.host=h),f.protocol=m.headers.get("x-forwarded-proto")??f.protocol,f.pathname=t(f.pathname,p.locales,p.localePrefix);const x=n(p.locales,p.localePrefix,!1).flatMap((([e,a])=>{function t(e){return"/"===e?a:a+e}let n;if(p.domains){return p.domains.filter((a=>o(e,a))).map((a=>{n=new URL(f),n.port="",n.host=a.domain,n.pathname=d(f.pathname,e);const o=a.localePrefix||p.localePrefix.mode;return e===a.defaultLocale&&"always"!==o||(n.pathname=t(n.pathname)),u(n,e)}))}{let a;a=i&&"object"==typeof i?d(f.pathname,e):f.pathname,e===p.defaultLocale&&"always"!==p.localePrefix.mode||(a=t(a)),n=new URL(a,f)}return u(n,e)}));if(!p.domains||0===p.domains.length){const e=d(f.pathname,p.defaultLocale);if(e){const a=new URL(e,f);x.push(u(a,"x-default"))}}return x.join(", ")}export{s as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/middleware/middleware.js b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..31bd31e320f9c979d8239e6a7ffe4933cf5e4323 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/middleware.js @@ -0,0 +1 @@ +import{NextResponse as e}from"next/server";import{receiveRoutingConfig as t}from"../routing/config.js";import{HEADER_LOCALE_NAME as r}from"../shared/constants.js";import{matchesPathname as a,normalizeTrailingSlash as o,getLocalePrefix as n,getLocalizedTemplate as l}from"../shared/utils.js";import s from"./getAlternateLinksHeaderValue.js";import i from"./resolveLocale.js";import c from"./syncCookie.js";import{sanitizePathname as d,isLocaleSupportedOnDomain as f,getNormalizedPathname as m,getPathnameMatch as h,getInternalTemplate as x,formatTemplatePathname as p,formatPathname as u,getBestMatchingDomain as U,applyBasePath as P,getLocaleAsPrefix as g}from"./utils.js";function v(v){const L=t(v);return function(t){let v;try{v=decodeURI(t.nextUrl.pathname)}catch{return e.next()}const j=d(v),{domain:w,locale:k}=i(L,t.headers,t.cookies,j),b=w?w.defaultLocale===k:k===L.defaultLocale,q=L.domains?.filter((e=>f(k,e)))||[],R=null!=L.domains&&!w;function y(a){const n=new URL(a,t.url);t.nextUrl.basePath&&(n.pathname=P(n.pathname,t.nextUrl.basePath));const l=new Headers(t.headers);l.set(r,k);return o(t.nextUrl.pathname)!==o(n.pathname)?e.rewrite(n,{request:{headers:l}}):e.next({request:{headers:l}})}function H(r,a){const n=new URL(r,t.url);if(n.pathname=o(n.pathname),q.length>0&&!a&&w){const e=U(w,k,q);if(e){a=e.domain;const t=e.localePrefix||L.localePrefix.mode;e.defaultLocale===k&&"as-needed"===t&&(n.pathname=m(n.pathname,L.locales,L.localePrefix))}}if(a&&(n.host=a,t.headers.get("x-forwarded-host"))){n.protocol=t.headers.get("x-forwarded-proto")??t.nextUrl.protocol;const e=a.split(":")[1];n.port=e??t.headers.get("x-forwarded-port")??""}return t.nextUrl.basePath&&(n.pathname=P(n.pathname,t.nextUrl.basePath)),V=!0,e.redirect(n.toString())}const z=m(j,L.locales,L.localePrefix),A=h(j,L.locales,L.localePrefix,w),C=null!=A,I=w?.localePrefix||L.localePrefix.mode,N="never"===I||b&&"as-needed"===I;let S,T,V,B=z;const D=L.pathnames;if(D){let e;if([e,T]=x(D,z,k),T){const r=D[T],o=l(r,k,T);if(a(o,z))B=p(z,o,T);else{let a;a=e?l(r,e,T):T;const s=N?void 0:n(k,L.localePrefix),i=p(z,a,o);S=H(u(i,s,t.nextUrl.search))}}}if(!S)if("/"!==B||C){const e=u(B,g(k),t.nextUrl.search);if(C){const r=u(z,A.prefix,t.nextUrl.search);if("never"===I)S=H(u(z,void 0,t.nextUrl.search));else if(A.exact)if(b&&N)S=H(u(z,void 0,t.nextUrl.search));else if(L.domains){const t=U(w,A.locale,q);S=w?.domain===t?.domain||R?y(e):H(r,t?.domain)}else S=y(e);else S=H(r)}else S=N?y(e):H(u(z,n(k,L.localePrefix),t.nextUrl.search))}else S=N?y(u(B,g(k),t.nextUrl.search)):H(u(z,n(k,L.localePrefix),t.nextUrl.search));return c(t,S,k,L,w),!V&&"never"!==I&&L.alternateLinks&&L.locales.length>1&&S.headers.set("Link",s({routing:L,internalTemplateName:T,localizedPathnames:null!=T&&D?D[T]:void 0,request:t,resolvedLocale:k})),S}}export{v as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/middleware/resolveLocale.js b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/resolveLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..a3b9e5dc6dd4d49efd3e3b95f675b57bc0e62fe7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/resolveLocale.js @@ -0,0 +1 @@ +import{match as e}from"@formatjs/intl-localematcher";import o from"negotiator";import{getPathnameMatch as l,isLocaleSupportedOnDomain as t,getHost as n}from"./utils.js";function a(l,t,n){let a;const c=new o({headers:{"accept-language":l.get("accept-language")||void 0}}).languages();try{const o=function(e){return e.slice().sort(((e,o)=>o.length-e.length))}(t);a=function(e,o){return e.find((e=>e.toLowerCase()===o.toLowerCase()))}(t,e(c,o,n))}catch{}return a}function c(e,o){if(e.localeCookie&&o.has(e.localeCookie.name)){const l=o.get(e.localeCookie.name)?.value;if(l&&e.locales.includes(l))return l}}function i(e,o,t,n){let i;return n&&(i=l(n,e.locales,e.localePrefix)?.locale),!i&&e.localeDetection&&(i=c(e,t)),!i&&e.localeDetection&&(i=a(o,e.locales,e.defaultLocale)),i||(i=e.defaultLocale),i}function r(e,o,r,f){const u=function(e,o){const l=n(e);if(l)return o.find((e=>e.domain===l))}(o,e.domains);if(!u)return{locale:i(e,o,r,f)};let s;if(f){const o=l(f,e.locales,e.localePrefix,u)?.locale;if(o){if(!t(o,u))return{locale:o,domain:u};s=o}}if(!s&&e.localeDetection){const o=c(e,r);o&&t(o,u)&&(s=o)}if(!s&&e.localeDetection){const e=a(o,u.locales,u.defaultLocale);e&&(s=e)}return s||(s=u.defaultLocale),{locale:s,domain:u}}function f(e,o,l,t){return e.domains?r(e,o,l,t):{locale:i(e,o,l,t)}}export{f as default,a as getAcceptLanguageLocale}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/middleware/syncCookie.js b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/syncCookie.js new file mode 100644 index 0000000000000000000000000000000000000000..063dabf222fa3859593dbbd3320a4334b98faaa5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/syncCookie.js @@ -0,0 +1 @@ +import{getAcceptLanguageLocale as e}from"./resolveLocale.js";function o(o,t,s,a,l){if(!a.localeCookie)return;const c=o.headers.get("sec-fetch-dest");if(null!=c&&"document"!==c)return;const{name:i,...r}=a.localeCookie,n=o.cookies.has(i);if(n&&o.cookies.get(i)?.value!==s)t.cookies.set(i,s,{path:o.nextUrl.basePath||void 0,...r});else if(!n){e(o.headers,l?.locales||a.locales,a.defaultLocale)!==s&&t.cookies.set(i,s,{path:o.nextUrl.basePath||void 0,...r})}}export{o as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/middleware/utils.js b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..379ce60a5d84819a2798c5e7d486b0c9756a3092 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/middleware/utils.js @@ -0,0 +1 @@ +import{normalizeTrailingSlash as e,getSortedPathnames as t,matchesPathname as n,prefixPathname as r,getLocalePrefix as o,templateToRegex as c,getLocalizedTemplate as i}from"../shared/utils.js";function s(e,r,o){const c=t(Object.keys(e));for(const t of c){const c=e[t];if("string"==typeof c){if(n(c,r))return[void 0,t]}else{const s=Object.entries(c),f=s.findIndex((([e])=>e===o));f>0&&s.unshift(s.splice(f,1)[0]);for(const[o]of s){const c=i(e[t],o,t);if(n(c,r))return[o,t]}}}for(const t of Object.keys(e))if(n(t,r))return[void 0,t];return[void 0,void 0]}function f(t,n,r,o){let c="";return c+=p(r,d(n,t)),c=e(c),c}function l(t,n,r){t.endsWith("/")||(t+="/");const o=u(n,r),c=new RegExp(`^(${o.map((([,e])=>e.replaceAll("/","\\/"))).join("|")})/(.*)`,"i"),i=t.match(c);let s=i?"/"+i[2]:t;return"/"!==s&&(s=e(s)),s}function u(e,t,n=!0){const r=e.map((e=>[e,o(e,t)]));return n&&r.sort(((e,t)=>t[1].length-e[1].length)),r}function a(e,t,n,r){const o=u(t,n);r&&o.sort((([e],[t])=>{if(e===r.defaultLocale)return-1;if(t===r.defaultLocale)return 1;const n=r.locales.includes(e),o=r.locales.includes(t);return n&&!o?-1:!n&&o?1:0}));for(const[t,n]of o){let r,o;if(e===n||e.startsWith(n+"/"))r=o=!0;else{const t=e.toLowerCase(),c=n.toLowerCase();(t===c||t.startsWith(c+"/"))&&(r=!1,o=!0)}if(o)return{locale:t,prefix:n,matchedPrefix:e.slice(0,n.length),exact:r}}}function d(t,n){const r=e(n),o=e(t),i=c(o).exec(r);if(!i)return;const s={},f=o.match(/\[([^\]]+)\]/g)??[];for(let e=1;e{n=n.replace(`[${e}]`,(()=>t))})),n}function g(e,t,n){let o=e;return t&&(o=r(t,o)),n&&(o+=n),o}function h(e){return e.get("x-forwarded-host")??e.get("host")??void 0}function x(e,t){return t.defaultLocale===e||t.locales.includes(e)}function m(e,t,n){let r;return e&&x(t,e)&&(r=e),r||(r=n.find((e=>e.defaultLocale===t))),r||(r=n.find((e=>e.locales.includes(t)))),r}function j(t,n){return e(n+t)}function L(e){return`/${e}`}function v(e){return e.replace(/\\/g,"%5C").replace(/[\t\n\r]/g,"").replace(/\/+/g,"/")}export{j as applyBasePath,g as formatPathname,p as formatPathnameTemplate,f as formatTemplatePathname,m as getBestMatchingDomain,h as getHost,s as getInternalTemplate,L as getLocaleAsPrefix,u as getLocalePrefixes,l as getNormalizedPathname,a as getPathnameMatch,d as getRouteParams,x as isLocaleSupportedOnDomain,v as sanitizePathname}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation.react-client.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation.react-client.js new file mode 100644 index 0000000000000000000000000000000000000000..67df908f12860e172fe7fc5471e29f034c47f1aa --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation.react-client.js @@ -0,0 +1 @@ +export{default as createNavigation}from"./navigation/react-client/createNavigation.js"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation.react-server.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation.react-server.js new file mode 100644 index 0000000000000000000000000000000000000000..864493c5204ae5ee2d5f2b2eb63d39d846a50136 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation.react-server.js @@ -0,0 +1 @@ +export{default as createNavigation}from"./navigation/react-server/createNavigation.js"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-client/createNavigation.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-client/createNavigation.js new file mode 100644 index 0000000000000000000000000000000000000000..7ecb8c562f17a8a66116127e58b1f4c079440a5a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-client/createNavigation.js @@ -0,0 +1 @@ +import{useRouter as e}from"next/navigation";import{useMemo as t}from"react";import{useLocale as r}from"use-intl";import o from"../shared/createSharedNavigationFns.js";import n from"../shared/syncLocaleCookie.js";import{getRoute as a}from"../shared/utils.js";import s from"./useBasePathname.js";function i(i){const{Link:c,config:u,getPathname:m,...f}=o(r,i);return{...f,Link:c,usePathname:function(){const e=s(u),o=r();return t((()=>e&&u.pathnames?a(o,e,u.pathnames):e),[o,e])},useRouter:function(){const o=e(),a=r();return t((()=>{function e(e){return function(t,r){const{locale:o,...s}=r||{},i=[m({href:t,locale:o||a,forcePrefix:null!=o||void 0})];Object.keys(s).length>0&&i.push(s),n(u.localeCookie,a,o),e(...i)}}return{...o,push:e(o.push),replace:e(o.replace),prefetch:e(o.prefetch)}}),[a,o])},getPathname:m}}export{i as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-client/useBasePathname.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-client/useBasePathname.js new file mode 100644 index 0000000000000000000000000000000000000000..8a5547acf8e1c68f295dac6f8d2f943b01f4beb5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-client/useBasePathname.js @@ -0,0 +1 @@ +import{usePathname as e}from"next/navigation";import{useMemo as r}from"react";import{useLocale as o}from"use-intl";import{hasPathnamePrefixed as t,unprefixPathname as i,getLocalePrefix as f,getLocaleAsPrefix as l}from"../../shared/utils.js";function n(n){const s=e(),a=o();return r((()=>{if(!s)return s;let e=s;const r=f(a,n.localePrefix);if(t(r,s))e=i(s,r);else if("never"!==n.localePrefix.mode&&n.localePrefix.prefixes){const r=l(a);t(r,s)&&(e=i(s,r))}return e}),[n.localePrefix,a,s])}export{n as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-server/createNavigation.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-server/createNavigation.js new file mode 100644 index 0000000000000000000000000000000000000000..77fd9aec2ad1b3d90994ec170817295e5adfdc49 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-server/createNavigation.js @@ -0,0 +1 @@ +import e from"../shared/createSharedNavigationFns.js";import o from"./getServerLocale.js";function t(t){const{config:n,...r}=e(o,t);function a(e){return()=>{throw new Error(`\`${e}\` is not supported in Server Components. You can use this hook if you convert the calling component to a Client Component.`)}}return{...r,usePathname:a("usePathname"),useRouter:a("useRouter")}}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-server/getServerLocale.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-server/getServerLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..c1a1ce786abca77bf313dc67851b8de6169bef14 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/react-server/getServerLocale.js @@ -0,0 +1 @@ +import e from"../../server/react-server/getConfig.js";async function r(){return(await e()).locale}export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/BaseLink.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/BaseLink.js new file mode 100644 index 0000000000000000000000000000000000000000..cc0884fe33c26e4a56dbe67499b7a9122b67ae2d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/BaseLink.js @@ -0,0 +1,2 @@ +"use client"; +import o from"next/link";import{forwardRef as e}from"react";import{useLocale as r}from"use-intl";import l from"./syncLocaleCookie.js";import{jsx as c}from"react/jsx-runtime";const n=o;function t({curLocale:o,linkRef:e,locale:r,localeCookie:t,onClick:i,prefetch:f,...a}){return c(n,{ref:e,hrefLang:r,onClick:function(e){l(t,o,r),i&&i(e)},prefetch:!1,...a})}function i({locale:o,localeCookie:e,...l},i){const f=r();return null!=o&&o!==f?c(t,{curLocale:f,linkRef:i,locale:o,localeCookie:e,...l}):c(n,{ref:i,...l})}var f=e(i);export{f as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/createSharedNavigationFns.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/createSharedNavigationFns.js new file mode 100644 index 0000000000000000000000000000000000000000..8915bfd17b72feccc9b9c2565b42f2eeb7f93047 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/createSharedNavigationFns.js @@ -0,0 +1 @@ +import{redirect as e,permanentRedirect as t}from"next/navigation";import{forwardRef as o}from"react";import{receiveRoutingConfig as r}from"../../routing/config.js";import n from"../../shared/use.js";import{isLocalizableHref as a,isPromise as i}from"../../shared/utils.js";import c from"./BaseLink.js";import{serializeSearchParams as f,compileLocalizedPathname as m,applyPathnamePrefix as l,normalizeNameOrNameWithParams as s}from"./utils.js";import{jsx as p}from"react/jsx-runtime";function u(u,h){const j=r(h||{}),d=j.pathnames;function g({href:e,locale:t,...o},r){let f,m;"object"==typeof e?(f=e.pathname,m=e.params):f=e;const l=a(e),s=u(),h=i(s)?n(s):s,g=l?y({locale:t||h,href:null==d?f:{pathname:f,params:m},forcePrefix:null!=t||void 0}):f;return p(c,{ref:r,href:"object"==typeof e?{...e,pathname:g}:g,locale:t,localeCookie:j.localeCookie,...o})}const x=o(g);function y(e){const{forcePrefix:t,href:o,locale:r}=e;let n;return null==d?"object"==typeof o?(n=o.pathname,o.query&&(n+=f(o.query))):n=o:n=m({locale:r,...s(o),pathnames:j.pathnames}),l(n,r,j,t)}function k(e){return function(t,...o){return e(y(t),...o)}}const b=k(e),P=k(t);return{config:j,Link:x,redirect:b,permanentRedirect:P,getPathname:y}}export{u as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/syncLocaleCookie.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/syncLocaleCookie.js new file mode 100644 index 0000000000000000000000000000000000000000..7f99affd7d2ec63fa7773df13645b17a25d560a7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/syncLocaleCookie.js @@ -0,0 +1 @@ +import{getBasePath as t}from"./utils.js";function e(e,o,n){if(!e||!(n!==o&&null!=n))return;const{name:a,...f}=e;f.path||(f.path=t()||"/");let r=`${a}=${n};`;for(const[t,e]of Object.entries(f)){r+=`${"maxAge"===t?"max-age":t}`,"boolean"!=typeof e&&(r+="="+e),r+=";"}document.cookie=r}export{e as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/utils.js b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..ca223465f6d5a4baf76e160af35e9d38a548bd5a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/navigation/shared/utils.js @@ -0,0 +1 @@ +import{getSortedPathnames as e,matchesPathname as t,isLocalizableHref as n,prefixPathname as r,normalizeTrailingSlash as o,getLocalizedTemplate as a,getLocalePrefix as c}from"../../shared/utils.js";function i(e){return"string"==typeof e?{pathname:e}:e}function s(e){function t(e){return String(e)}const n=new URLSearchParams;for(const[r,o]of Object.entries(e))Array.isArray(o)?o.forEach((e=>{n.append(r,t(e))})):n.set(r,t(o));return"?"+n.toString()}function f({pathname:e,locale:t,params:n,pathnames:r,query:c}){function i(e){const i=r[e];let f;if(i){const r=a(i,t,e);f=r,n&&Object.entries(n).forEach((([e,t])=>{let n,r;Array.isArray(t)?(n=`(\\[)?\\[...${e}\\](\\])?`,r=t.map((e=>String(e))).join("/")):(n=`\\[${e}\\]`,r=String(t)),f=f.replace(new RegExp(n,"g"),(()=>r))})),f=f.replace(/\[\[\.\.\..+\]\]/g,""),f=function(e){return new URL(e,"http://l").pathname}(f)}else f=e;return f=o(f),c&&(f+=s(c)),f}if("string"==typeof e)return i(e);{const{pathname:t,...n}=e;return{...n,pathname:i(t)}}}function l(n,r,o){const c=e(Object.keys(o)),i=decodeURI(r);for(const e of c){const r=o[e];if("string"==typeof r){if(t(r,i))return e}else if(t(a(r,n,e),i))return e}return r}function u(){try{return process.env._next_intl_base_path||""}catch{return""}}function p(e,t,o,a){const{mode:i}=o.localePrefix;let s;if(void 0!==a)s=a;else if(n(e)){const e=o.domains?.find((e=>e.locales.includes(t))),n=e?.localePrefix||i;"always"===n?s=!0:"as-needed"===n&&(s=e?t!==e.defaultLocale:t!==o.defaultLocale)}return s?r(c(t,o.localePrefix),e):e}export{p as applyPathnamePrefix,f as compileLocalizedPathname,u as getBasePath,l as getRoute,i as normalizeNameOrNameWithParams,s as serializeSearchParams}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..574ac01919379c2806fee36a11e61953257cbd84 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin.js @@ -0,0 +1 @@ +export{default}from"./plugin/createNextIntlPlugin.js"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/config.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/config.js new file mode 100644 index 0000000000000000000000000000000000000000..2474a3af1f7284a5fd8b84965eda231a7caed4a6 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/config.js @@ -0,0 +1 @@ +const e="NODE_ENV".trim(),s="development"===process.env[e],o=process.argv.includes("build"),r=s||o;export{s as isDevelopment,r as isDevelopmentOrNextBuild,o as isNextBuild}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/createNextIntlPlugin.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/createNextIntlPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d33469bb04b3dc47de47b31144c9f365987fa5c9 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/createNextIntlPlugin.js @@ -0,0 +1 @@ +import e from"../extractor/normalizeExtractorConfig.js";import t from"./extractor/initExtractionCompiler.js";import r from"./getNextConfig.js";import{warn as o}from"./utils.js";import n from"./declaration/createMessagesDeclaration.js";function s(s,i){null!=i?.i18n&&o("An `i18n` property was found in your Next.js config. This likely causes conflicts and should therefore be removed if you use the App Router.\n\nIf you're in progress of migrating from the Pages Router, you can refer to this example: https://next-intl.dev/examples#app-router-migration\n");const a=function(){const e=process.argv[1];if(!e)return!1;return e.replace(/\\/g,"/").includes("/telemetry/detached-flush")}(),c=s.experimental?.createMessagesDeclaration;let f;c&&!a&&n("string"==typeof c?[c]:c);const u=s.experimental,l=u?.extract;return l&&(f=e({extract:l,messages:u.messages,srcPath:u.srcPath})),a||t(f),r(s,i,f)}function i(e={}){const t="string"==typeof e?{requestConfig:e}:e;return function(e){return s(t,e)}}export{i as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/declaration/createMessagesDeclaration.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/declaration/createMessagesDeclaration.js new file mode 100644 index 0000000000000000000000000000000000000000..9f606e1e69e09d7be74c8da5fa2eaf54d1288288 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/declaration/createMessagesDeclaration.js @@ -0,0 +1 @@ +import e from"fs";import t from"path";import{once as s,throwError as o}from"../utils.js";import n from"../watchFile.js";const i=s("_NEXT_INTL_COMPILE_MESSAGES");function r(s){["info","start"].some((e=>process.argv.includes(e)))||i((()=>{for(const n of s){const s=t.resolve(n);e.existsSync(s)||o(`\`createMessagesDeclaration\` points to a non-existent file: ${s}`),s.endsWith(".json")||o(`\`createMessagesDeclaration\` needs to point to a JSON file. Received: ${s}`);const i=process.env["NODE_ENV".trim()];a(n),"development"===i&&c(n)}}))}function c(e){const t=n(e,(()=>{a(e,!0)}));process.on("exit",(()=>{t.close()}))}function a(t,s=!1){const o=t.replace(/\.json$/,".d.json.ts");function n(e){return`// This file is auto-generated by next-intl, do not edit directly.\n// See: https://next-intl.dev/docs/workflows/typescript#messages-arguments\n\ndeclare const messages: ${e.trim()};\nexport default messages;`}if(s)return e.promises.readFile(t,"utf-8").then((t=>e.promises.writeFile(o,n(t))));const i=e.readFileSync(t,"utf-8");e.writeFileSync(o,n(i))}export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/extractor/initExtractionCompiler.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/extractor/initExtractionCompiler.js new file mode 100644 index 0000000000000000000000000000000000000000..613776052a70c1b81887e5284e4a60284f6d53e2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/extractor/initExtractionCompiler.js @@ -0,0 +1 @@ +import o from"../../extractor/ExtractionCompiler.js";import{hasLocalesToExtract as t}from"../../extractor/utils.js";import{isDevelopment as r,isNextBuild as e}from"../config.js";import{once as s}from"../utils.js";let i;const c=s("_NEXT_INTL_EXTRACT");function n(s){if(!s||!t(s))return;(r||e)&&c((()=>{function t(){i&&(i[Symbol.dispose](),i=void 0)}i=new o(s,{isDevelopment:r,projectRoot:process.cwd()}),i.extractAll(),process.on("exit",t),process.on("SIGINT",t),process.on("SIGTERM",t)}))}export{n as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/getNextConfig.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/getNextConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..a68b6e71d038df353dbe81223c092238fde6da74 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/getNextConfig.js @@ -0,0 +1 @@ +import e from"fs";import{createRequire as t}from"module";import r from"path";import{getFormatExtension as o}from"../extractor/format/index.js";import{normalizeMessagesCatalogPaths as s}from"../extractor/normalizeExtractorConfig.js";import n from"../extractor/source/SourceFileFilter.js";import{isDevelopmentOrNextBuild as a}from"./config.js";import{isNextJs16OrHigher as i,hasStableTurboConfig as l}from"./nextFlags.js";import{throwError as u}from"./utils.js";const c=t(import.meta.url);function m(e){return[`${e}.ts`,`${e}.tsx`,`${e}.js`,`${e}.jsx`]}function p(e){return Array.isArray(e)?e.map(p):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)).map((([e,t])=>[e,p(t)]))):e}function f(t,o){function s(t){return e.existsSync(function(e){const t=[];return o&&t.push(o),t.push(e),r.resolve(...t)}(t))}if(t)return a&&!s(t)&&u(`Could not find i18n config at ${t}, please provide a valid path.`),t;for(const e of[...m("./i18n/request"),...m("./src/i18n/request")])if(s(e))return e;return a&&u("Could not locate request configuration module.\n\nThis path is supported by default: ./(src/)i18n/request.{js,jsx,ts,tsx}\n\nAlternatively, you can specify a custom location in your Next.js config:\n\nconst withNextIntl = createNextIntlPlugin(\n './path/to/i18n/request.tsx'\n);"),s("./src")?"./src/i18n/request.ts":"./i18n/request.ts"}function x(e,t,a){const m=null!=process.env.TURBOPACK,x=m||i(),g={};let d=[];function v(e){return{loader:"next-intl/extractor/extractionLoader",options:p(e)}}function b(){const t=e.experimental,r=t.messages,o=r.sourceLocale??("object"==typeof t.extract?t.extract.sourceLocale:void 0);return{loader:"next-intl/extractor/catalogLoader",options:p({messages:{format:r.format,precompile:r.precompile,sourceLocale:o}})}}function h(){return t?.turbopack?.rules||t?.experimental?.turbo?.rules||{}}function j(e,t,r){e[t]?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:e[t]=r}if(e.experimental?.messages&&(d=s(e.experimental.messages.path)),x){e.requestConfig&&r.isAbsolute(e.requestConfig)&&u("Turbopack support for next-intl currently does not support absolute paths, please provide a relative one (e.g. './src/i18n/config.ts').\n\nFound: "+e.requestConfig);const s={"next-intl/config":f(e.requestConfig)};if(e.experimental?.messages?.precompile){let e=r.relative(process.cwd(),c.resolve("use-intl/format-message/format-only"));e.startsWith(".")||(e=`./${e}`),s["use-intl/format-message"]=e.replace(/\\/g,"/")}let m;if(e.experimental?.extract&&(i()||u("Message extraction requires Next.js 16 or higher."),m??=h(),j(m,`*.{${n.EXTENSIONS.join(",")}}`,{loaders:[v(a)],condition:{content:/(useExtracted|getExtracted)/}})),e.experimental?.messages){i()||u("Message catalog loading requires Next.js 16 or higher."),m??=h();j(m,`*${o(e.experimental.messages.format)}`,{loaders:[b()],condition:{path:`{${d.join(",")}}/**/*`},as:"*.js"})}l()&&!t?.experimental?.turbo?g.turbopack={...t?.turbopack,...m&&{rules:m},resolveAlias:{...t?.turbopack?.resolveAlias,...s}}:g.experimental={...t?.experimental,turbo:{...t?.experimental?.turbo,...m&&{rules:m},resolveAlias:{...t?.experimental?.turbo?.resolveAlias,...s}}}}m||(g.webpack=function(s,i){if(s.resolve||(s.resolve={}),s.resolve.alias||(s.resolve.alias={}),s.resolve.alias["next-intl/config"]=r.resolve(s.context,f(e.requestConfig,s.context)),e.experimental?.messages?.precompile&&(s.resolve.alias["use-intl/format-message"]=c.resolve("use-intl/format-message/format-only")),e.experimental?.extract&&(s.module||(s.module={}),s.module.rules||(s.module.rules=[]),s.module.rules.push({test:new RegExp(`\\.(${n.EXTENSIONS.join("|")})$`),use:[v(a)]})),e.experimental?.messages){s.module||(s.module={}),s.module.rules||(s.module.rules=[]);const t=o(e.experimental.messages.format);s.module.rules.push({test:new RegExp(`${t.replace(/\./g,"\\.")}$`),include:d.map((e=>r.resolve(s.context,e))),use:[b()],type:"javascript/auto"})}return"function"==typeof t?.webpack?t.webpack(s,i):s});const y={};return t?.trailingSlash&&(y._next_intl_trailing_slash="true"),t?.basePath&&(y._next_intl_base_path=t.basePath),Object.keys(y).length>0&&(g.env={...t?.env,...y}),Object.assign({},t,g)}export{x as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/nextFlags.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/nextFlags.js new file mode 100644 index 0000000000000000000000000000000000000000..1d1e04a4b9ffcf274fbd34aadeda1ff993375b72 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/nextFlags.js @@ -0,0 +1 @@ +import{createRequire as t}from"module";function r(){try{const r=t(import.meta.url);return r("next/package.json").version}catch(t){throw new Error("Failed to get current Next.js version. This can happen if next-intl/plugin is imported into your app code outside of your next.config.js.",{cause:t})}}function n(t,r){const n=t.split(".").map(Number),e=r.split(".").map(Number);for(let t=0;t<3;t++){const r=n[t]||0,o=e[t]||0;if(r>o)return 1;if(r=0}function o(){return n(r(),"16.0.0")>=0}export{e as hasStableTurboConfig,o as isNextJs16OrHigher}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/utils.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..14d30ed085d4ece69761396ab39b7a9602f88ebc --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/utils.js @@ -0,0 +1 @@ +function n(n){return`\n[next-intl] ${n}\n`}function o(o){throw new Error(n(o))}function r(o){console.warn(n(o))}function t(n){return function(o){"1"!==process.env[n]&&(process.env[n]="1",o())}}export{t as once,o as throwError,r as warn}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/plugin/watchFile.js b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/watchFile.js new file mode 100644 index 0000000000000000000000000000000000000000..f59328fb6867f3944eb59d511babfd0b0739c885 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/plugin/watchFile.js @@ -0,0 +1 @@ +import r from"fs";import t from"path";function e(e,a){const n=t.dirname(e),o=t.basename(e);return r.watch(n,{persistent:!1,recursive:!1},((r,t)=>{t===o&&a()}))}export{e as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-client/index.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-client/index.js new file mode 100644 index 0000000000000000000000000000000000000000..02994bf0cbd87263fa4b6627464144c4b6e95b4a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-client/index.js @@ -0,0 +1 @@ +import{useFormatter as r,useTranslations as t}from"use-intl";function o(r,t){return(...r)=>{try{return t(...r)}catch{throw new Error(void 0)}}}const n=o(0,t),e=o(0,r);export{e as useFormatter,n as useTranslations}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/NextIntlClientProviderServer.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/NextIntlClientProviderServer.js new file mode 100644 index 0000000000000000000000000000000000000000..66ed7aefc22e847058e9f53d985f1b2221d60458 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/NextIntlClientProviderServer.js @@ -0,0 +1 @@ +import e from"../server/react-server/getConfigNow.js";import r from"../server/react-server/getFormats.js";import t from"../shared/NextIntlClientProvider.js";import{jsx as o}from"react/jsx-runtime";import s from"../server/react-server/getTimeZone.js";import a from"../server/react-server/getMessages.js";import m from"../server/react-server/getLocale.js";async function i({formats:i,locale:n,messages:v,now:f,timeZone:c,...g}){return o(t,{formats:void 0===i?await r():i,locale:n??await m(),messages:void 0===v?await a():v,now:f??await e(),timeZone:c??await s(),...g})}export{i as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useConfig.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..2a61e0fe48ce12309c981624e46dca5fd2db800f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useConfig.js @@ -0,0 +1 @@ +import e from"../server/react-server/getConfig.js";import n from"../shared/use.js";function r(r){return function(e,r){try{return n(r)}catch(n){throw n instanceof TypeError&&n.message.includes("Cannot read properties of null (reading 'use')")?new Error(`\`${e}\` is not callable within an async component. Please refer to https://next-intl.dev/docs/environments/server-client-components#async-components`,{cause:n}):n}}(r,e())}export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useExtracted.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useExtracted.js new file mode 100644 index 0000000000000000000000000000000000000000..011b384ae053cd39d83f075bb58f689cac0283a7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useExtracted.js @@ -0,0 +1 @@ +import r from"../server/react-server/getServerExtractor.js";import e from"./useConfig.js";function t(t){const o=e("useExtracted");return r(o,t)}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useFormatter.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useFormatter.js new file mode 100644 index 0000000000000000000000000000000000000000..89587dad822b8a48cac5a59659dc815ac3c5bb55 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useFormatter.js @@ -0,0 +1 @@ +import r from"../server/react-server/getServerFormatter.js";import e from"./useConfig.js";function t(){const t=e("useFormatter");return r(t)}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useLocale.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..3cceb1921932bbcd094f5f55cbfbec91a82e7f96 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useLocale.js @@ -0,0 +1 @@ +import e from"./useConfig.js";function o(){return e("useLocale").locale}export{o as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useMessages.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useMessages.js new file mode 100644 index 0000000000000000000000000000000000000000..646913ae88b2e7dc45f423e80c41cb77ba12eff8 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useMessages.js @@ -0,0 +1 @@ +import{getMessagesFromConfig as e}from"../server/react-server/getMessages.js";import s from"./useConfig.js";function r(){const r=s("useMessages");return e(r)}export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useNow.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useNow.js new file mode 100644 index 0000000000000000000000000000000000000000..653124b6abf8101ef070a7b77fd4a97250c8065d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useNow.js @@ -0,0 +1 @@ +import e from"../server/react-server/getDefaultNow.js";import o from"./useConfig.js";function t(t){null!=t?.updateInterval&&console.error("`useNow` doesn't support the `updateInterval` option in Server Components, the value will be ignored. If you need the value to update, you can convert the component to a Client Component.");return o("useNow").now??e()}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useTimeZone.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useTimeZone.js new file mode 100644 index 0000000000000000000000000000000000000000..09c61f144e67aa87400b2e24720e9324ba49c6b8 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useTimeZone.js @@ -0,0 +1 @@ +import e from"./useConfig.js";function o(){return e("useTimeZone").timeZone}export{o as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useTranslations.js b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useTranslations.js new file mode 100644 index 0000000000000000000000000000000000000000..d24fa9b230a53e97a0b606351cbe12e2214f8c51 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/react-server/useTranslations.js @@ -0,0 +1 @@ +import r from"../server/react-server/getServerTranslator.js";import e from"./useConfig.js";function s(...[s]){const t=e("useTranslations");return r(t,s)}export{s as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/routing.js b/e-commerce/node_modules/next-intl/dist/esm/production/routing.js new file mode 100644 index 0000000000000000000000000000000000000000..4fd5fdc8306d5318d3aa480b92faaaf1df3dd158 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/routing.js @@ -0,0 +1 @@ +export{default as defineRouting}from"./routing/defineRouting.js"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/routing/config.js b/e-commerce/node_modules/next-intl/dist/esm/production/routing/config.js new file mode 100644 index 0000000000000000000000000000000000000000..ee4627826005b52911602a4ffab0b9ab202b5c63 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/routing/config.js @@ -0,0 +1 @@ +function e(e){return{...e,localePrefix:(a=e.localePrefix,"object"==typeof a?a:{mode:a||"always"}),localeCookie:(o=e.localeCookie,!!(o??1)&&{name:"NEXT_LOCALE",sameSite:"lax",..."object"==typeof o&&o}),localeDetection:e.localeDetection??!0,alternateLinks:e.alternateLinks??!0};var o,a}export{e as receiveRoutingConfig}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/routing/defineRouting.js b/e-commerce/node_modules/next-intl/dist/esm/production/routing/defineRouting.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f451a2430752de988451b062189c5afabfa927 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/routing/defineRouting.js @@ -0,0 +1 @@ +function t(t){return t}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server.react-client.js b/e-commerce/node_modules/next-intl/dist/esm/production/server.react-client.js new file mode 100644 index 0000000000000000000000000000000000000000..66fbf0b75d45dd90d26567de4f2040bbd5bf5759 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server.react-client.js @@ -0,0 +1 @@ +export{getExtracted,getFormatter,getLocale,getMessages,getNow,getRequestConfig,getTimeZone,getTranslations,setRequestLocale}from"./server/react-client/index.js"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server.react-server.js b/e-commerce/node_modules/next-intl/dist/esm/production/server.react-server.js new file mode 100644 index 0000000000000000000000000000000000000000..9c80270419909500cb462eea82a308368da442b0 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server.react-server.js @@ -0,0 +1 @@ +export{default as getRequestConfig}from"./server/react-server/getRequestConfig.js";export{default as getFormatter}from"./server/react-server/getFormatter.js";export{default as getNow}from"./server/react-server/getNow.js";export{default as getTimeZone}from"./server/react-server/getTimeZone.js";export{default as getExtracted}from"./server/react-server/getExtracted.js";export{default as getMessages}from"./server/react-server/getMessages.js";export{default as getLocale}from"./server/react-server/getLocale.js";export{default as getTranslations}from"./server/react-server/getTranslations.js";export{setCachedRequestLocale as setRequestLocale}from"./server/react-server/RequestLocaleCache.js"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-client/index.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-client/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bd0ebf70304687f611cf4c606b66476053399c4f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-client/index.js @@ -0,0 +1 @@ +function e(e){return()=>{throw new Error(`\`${e}\` is not supported in Client Components.`)}}function t(...t){return e("getRequestConfig")}const n=e("getFormatter"),o=e("getNow"),r=e("getTimeZone"),s=e("getMessages"),g=e("getLocale"),i=e("getExtracted"),a=e("getTranslations"),u=e("setRequestLocale");export{i as getExtracted,n as getFormatter,g as getLocale,s as getMessages,o as getNow,t as getRequestConfig,r as getTimeZone,a as getTranslations,u as setRequestLocale}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/RequestLocale.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/RequestLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..aec20562991ba437e5d81ccaa09c3616c0ebf11a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/RequestLocale.js @@ -0,0 +1 @@ +import{headers as t}from"next/headers";import{cache as e}from"react";import{HEADER_LOCALE_NAME as n}from"../../shared/constants.js";import{isPromise as r}from"../../shared/utils.js";import{getCachedRequestLocale as o}from"./RequestLocaleCache.js";const s=e((async function(){const e=t();return r(e)?await e:e}));const i=e((async function(){let t;try{t=(await s()).get(n)||void 0}catch(t){if(t instanceof Error&&"DYNAMIC_SERVER_USAGE"===t.digest){const e=new Error("Usage of next-intl APIs in Server Components currently opts into dynamic rendering. This limitation will eventually be lifted, but as a stopgap solution, you can use the `setRequestLocale` API to enable static rendering, see https://next-intl.dev/docs/routing/setup#static-rendering",{cause:t});throw e.digest=t.digest,e}throw t}return t}));async function a(){return o()||await i()}export{a as getRequestLocale}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/RequestLocaleCache.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/RequestLocaleCache.js new file mode 100644 index 0000000000000000000000000000000000000000..b1f7b31099dd6ee130ee5bc7c5d2c97b1f5d4bbb --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/RequestLocaleCache.js @@ -0,0 +1 @@ +import{cache as o}from"react";const n=o((function(){return{locale:void 0}}));function t(){return n().locale}function c(o){n().locale=o}export{t as getCachedRequestLocale,c as setCachedRequestLocale}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/createRequestConfig.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/createRequestConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..2ff507857da7b25b621e58f39821a263e3a96d66 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/createRequestConfig.js @@ -0,0 +1 @@ +import t from"next-intl/config";export{default}from"next-intl/config"; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getConfig.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..1274834bbf98fcd412905b5232be76fa39512a9d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getConfig.js @@ -0,0 +1 @@ +import{cache as e}from"react";import{initializeConfig as t,_createIntlFormatters as o,_createCache as r}from"use-intl/core";import{isPromise as n}from"../../shared/utils.js";import{getRequestLocale as i}from"./RequestLocale.js";import s from"next-intl/config";const a=e((function(){return Intl.DateTimeFormat().resolvedOptions().timeZone}));const c=e((async function(e,t){let o=e({locale:t,get requestLocale(){return t?Promise.resolve(t):i()}});if(n(o)&&(o=await o),!o.locale)throw new Error("No locale was returned from `getRequestConfig`.\n\nSee https://next-intl.dev/docs/usage/configuration#i18n-request");return o})),m=e(o),l=e(r);const u=e((async function(e){const o=await c(s,e);return{...t(o),_formatters:m(l()),timeZone:o.timeZone||a()}}));export{u as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getConfigNow.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getConfigNow.js new file mode 100644 index 0000000000000000000000000000000000000000..517e659ad7886ecbf13d601a015bad5af19bd222 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getConfigNow.js @@ -0,0 +1 @@ +import{cache as t}from"react";import o from"./getConfig.js";const r=t((async function(t){return(await o(t)).now}));export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getDefaultNow.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getDefaultNow.js new file mode 100644 index 0000000000000000000000000000000000000000..8326f961ff49b5229eaf11a12c43e48c3d01d6cf --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getDefaultNow.js @@ -0,0 +1 @@ +import{cache as t}from"react";const e=t((function(){return new Date}));export{e as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getExtracted.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getExtracted.js new file mode 100644 index 0000000000000000000000000000000000000000..ad96d4443aaac7fbd776a3e6592c88ad75b4ff3a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getExtracted.js @@ -0,0 +1 @@ +import{cache as t}from"react";import r from"./getConfig.js";import o from"./getServerExtractor.js";const e=t((async function(t){let e,a;"string"==typeof t?e=t:t&&(a=t.locale,e=t.namespace);const n=await r(a);return o(n,e)}));export{e as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getFormats.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getFormats.js new file mode 100644 index 0000000000000000000000000000000000000000..152feb5897b980abe4b22000e9c557a9111bdd0a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getFormats.js @@ -0,0 +1 @@ +import{cache as t}from"react";import o from"./getConfig.js";const r=t((async function(){return(await o()).formats}));export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getFormatter.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getFormatter.js new file mode 100644 index 0000000000000000000000000000000000000000..df64e0cc30228fb8726239d1fcd9d5c258e1c7be --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getFormatter.js @@ -0,0 +1 @@ +import{cache as t}from"react";import r from"./getConfig.js";import o from"./getServerFormatter.js";const e=t((async function(t){const e=await r(t);return o(e)}));async function n(t){return e(t?.locale)}export{n as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getLocale.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getLocale.js new file mode 100644 index 0000000000000000000000000000000000000000..5f887287d2c94687b1ebd6dc1a1c48eb8169f01a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getLocale.js @@ -0,0 +1 @@ +import{cache as t}from"react";import o from"./getConfig.js";const r=t((async function(){return(await o()).locale}));export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getMessages.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getMessages.js new file mode 100644 index 0000000000000000000000000000000000000000..2eb5b938a961f7f9932ec12bf8a97f14ef3cbb73 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getMessages.js @@ -0,0 +1 @@ +import{cache as e}from"react";import t from"./getConfig.js";function o(e){if(!e.messages)throw new Error("No messages found. Have you configured them correctly? See https://next-intl.dev/docs/configuration#messages");return e.messages}const n=e((async function(e){return o(await t(e))}));async function r(e){return n(e?.locale)}export{r as default,o as getMessagesFromConfig}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getNow.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getNow.js new file mode 100644 index 0000000000000000000000000000000000000000..58d700fa01c318c365a696d9640dcb361136dcd0 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getNow.js @@ -0,0 +1 @@ +import o from"./getConfigNow.js";import t from"./getDefaultNow.js";async function a(a){return await o(a?.locale)??t()}export{a as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getRequestConfig.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getRequestConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f451a2430752de988451b062189c5afabfa927 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getRequestConfig.js @@ -0,0 +1 @@ +function t(t){return t}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerExtractor.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerExtractor.js new file mode 100644 index 0000000000000000000000000000000000000000..7dba3cad1f2913497bbb53252ac1e14b8e02bd5e --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerExtractor.js @@ -0,0 +1 @@ +import{cache as t}from"react";import r from"./getServerTranslator.js";var a=t((function(t,a){throw r(t,a),new Error("[next-intl] `useExtracted` was called in production without compilation. Include modules that call `useExtracted` in `srcPath` and use `transpilePackages` for 3rd-party packages.")}));export{a as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerFormatter.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerFormatter.js new file mode 100644 index 0000000000000000000000000000000000000000..f18257ad35f503e21ca0b517b5a4b4b362a22413 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerFormatter.js @@ -0,0 +1 @@ +import{cache as t}from"react";import{createFormatter as o}from"use-intl/core";import r from"./getDefaultNow.js";const e=t((function(t){return o({...t,get now(){return t.now??r()}})}));export{e as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerTranslator.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerTranslator.js new file mode 100644 index 0000000000000000000000000000000000000000..6ec6edd4c15504876fe5b8fb51cbecb62c91df8b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getServerTranslator.js @@ -0,0 +1 @@ +import{cache as r}from"react";import{createTranslator as e}from"use-intl/core";var t=r((function(r,t){return e({...r,namespace:t})}));export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getTimeZone.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getTimeZone.js new file mode 100644 index 0000000000000000000000000000000000000000..19973a33a81e24b78b340e94f4bdb86b4ae35729 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getTimeZone.js @@ -0,0 +1 @@ +import{cache as t}from"react";import n from"./getConfig.js";const o=t((async function(t){return(await n(t)).timeZone}));async function r(t){return o(t?.locale)}export{r as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getTranslations.js b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getTranslations.js new file mode 100644 index 0000000000000000000000000000000000000000..6d3f01a893004776f8a82544ee002c18884805a2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/server/react-server/getTranslations.js @@ -0,0 +1 @@ +import{cache as r}from"react";import t from"./getConfig.js";import e from"./getServerTranslator.js";var o=r((async function(r){let o,a;"string"==typeof r?o=r:r&&(a=r.locale,o=r.namespace);const n=await t(a);return e(n,o)}));export{o as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/shared/NextIntlClientProvider.js b/e-commerce/node_modules/next-intl/dist/esm/production/shared/NextIntlClientProvider.js new file mode 100644 index 0000000000000000000000000000000000000000..5dba83e1ebd4fc7103544461ee46c3a1bf6b98d2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/shared/NextIntlClientProvider.js @@ -0,0 +1,2 @@ +"use client"; +import{IntlProvider as r}from"use-intl/react";import{jsx as o}from"react/jsx-runtime";function t({locale:t,...e}){if(!t)throw new Error(void 0);return o(r,{locale:t,...e})}export{t as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/shared/constants.js b/e-commerce/node_modules/next-intl/dist/esm/production/shared/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..20cb1e7e43067c2411baf0c84ba13a8cf97c23fd --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/shared/constants.js @@ -0,0 +1 @@ +const L="X-NEXT-INTL-LOCALE";export{L as HEADER_LOCALE_NAME}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/shared/use.js b/e-commerce/node_modules/next-intl/dist/esm/production/shared/use.js new file mode 100644 index 0000000000000000000000000000000000000000..f780ab92029e6935e999f80fe7820195d80bbd78 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/shared/use.js @@ -0,0 +1 @@ +import*as r from"react";var a=r["use".trim()];export{a as default}; diff --git a/e-commerce/node_modules/next-intl/dist/esm/production/shared/utils.js b/e-commerce/node_modules/next-intl/dist/esm/production/shared/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..ce546db7599efe2718e2fa0104246e88953e9c95 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/esm/production/shared/utils.js @@ -0,0 +1 @@ +function n(n){return function(n){return"object"==typeof n?null==n.host&&null==n.hostname:!/^[a-z]+:/i.test(n)}(n)&&!function(n){const t="object"==typeof n?n.pathname:n;return null!=t&&!t.startsWith("/")}(n)}function t(n,t){return n.replace(new RegExp(`^${t}`),"")||"/"}function e(n,t){let e=n;return/^\/(\?.*)?$/.test(t)&&(t=t.slice(1)),e+=t,e}function r(n,t){return t===n||t.startsWith(`${n}/`)}function u(n,t,e){return"string"==typeof n?n:n[t]||e}function i(n){const t=function(){try{return"true"===process.env._next_intl_trailing_slash}catch{return!1}}(),[e,...r]=n.split("#"),u=r.join("#");let i=e;if("/"!==i){const n=i.endsWith("/");t&&!n?i+="/":!t&&n&&(i=i.slice(0,-1))}return u&&(i+="#"+u),i}function c(n,t){const e=i(n),r=i(t);return s(e).test(r)}function o(n,t){return"never"!==t.mode&&t.prefixes?.[n]||f(n)}function f(n){return"/"+n}function s(n){const t=n.replace(/\/\[\[(\.\.\.[^\]]+)\]\]/g,"(?:/(.*))?").replace(/\[\[(\.\.\.[^\]]+)\]\]/g,"(?:/(.*))?").replace(/\[(\.\.\.[^\]]+)\]/g,"(.+)").replace(/\[([^\]]+)\]/g,"([^/]+)");return new RegExp(`^${t}$`)}function l(n){return n.includes("[[...")}function p(n){return n.includes("[...")}function a(n){return n.includes("[")}function h(n,t){const e=n.split("/"),r=t.split("/"),u=Math.max(e.length,r.length);for(let n=0;n; + [Symbol.dispose](): void; + private installExitHandlers; + private uninstallExitHandlers; +} diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogLocales.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogLocales.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c85c3461da330f20e2ad4d5a5c722f17d5fc7792 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogLocales.d.ts @@ -0,0 +1,29 @@ +import type { ExtractorConfig, Locale } from '../types.js'; +type LocaleChangeCallback = (params: { + added: Array; + removed: Array; +}) => unknown; +type CatalogLocalesParams = { + messagesDir: string; + sourceLocale: Locale; + extension: string; + locales: ExtractorConfig['extract']['locales']; +}; +export default class CatalogLocales { + private messagesDir; + private extension; + private sourceLocale; + private locales; + private watcher?; + private targetLocales?; + private onChangeCallbacks; + constructor(params: CatalogLocalesParams); + getTargetLocales(): Promise>; + private readTargetLocales; + subscribeLocalesChange(callback: LocaleChangeCallback): void; + unsubscribeLocalesChange(callback: LocaleChangeCallback): void; + private startWatcher; + private stopWatcher; + private onChange; +} +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogManager.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogManager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4815a3ccf769b4f6b3cd45421039c341c134dd45 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogManager.d.ts @@ -0,0 +1,76 @@ +import type MessageExtractor from '../extractor/MessageExtractor.js'; +import type { ExtractorConfig } from '../types.js'; +export default class CatalogManager implements Disposable { + /** + * Extraction-derived fields aggregated into `ExtractorMessage`. + * Source code is the source of truth for these fields, only ancillary + * codec fields may merge from disk (e.g. flags). + */ + private static readonly extractorOwnedAggregatorKeys; + private config; + /** + * Source of truth for statically extracted source messages, + * grouped by file and message ID. + */ + private sourceMessagesByFile; + /** + * Reverse index for rebuilding aggregated messages without scanning all files. + * Contains the same `SourceExtractedMessage` arrays as `sourceMessagesByFile` and is + * kept in sync with it. + */ + private sourceMessagesById; + /** + * Fast lookup for messages by ID, aggregated across all files. This combines + * metadata from `sourceMessagesById`, e.g. references and descriptions. + */ + private messagesById; + /** + * This potentially also includes outdated ones that were initially available, + * but are not used anymore. This allows to restore them if they are used again. + **/ + private translationsByTargetLocale; + private lastWriteByLocale; + private saveScheduler; + private projectRoot; + private isDevelopment; + private persister?; + private codec?; + private catalogLocales?; + private extractor; + private sourceWatcher?; + private loadCatalogsPromise?; + private scanCompletePromise?; + constructor(config: ExtractorConfig, opts: { + extractor: MessageExtractor; + isDevelopment?: boolean; + projectRoot?: string; + saveDebounceMs?: number; + sourceMap?: boolean; + }); + private getCodec; + private getPersister; + private getCatalogLocales; + private getTargetLocales; + private getSrcPaths; + loadMessages(): Promise; + private loadSourceMessages; + private loadLocaleMessages; + private loadTargetMessages; + private reloadLocaleCatalog; + private mergeSourceDiskMetadata; + private processFile; + private extractFile; + private applyFileMessages; + private groupSourceMessagesById; + private rebuildMessageById; + private mergeDescriptions; + private haveMessagesChangedForFile; + private areSourceMessageArraysEqual; + private areSourceMessagesEqual; + save(): Promise; + private saveImpl; + private saveLocale; + private onLocalesChange; + private handleFileEvents; + [Symbol.dispose](): void; +} diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogPersister.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogPersister.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..28dcd7e357535997efc035d60ebfd6605d9fad0d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/CatalogPersister.d.ts @@ -0,0 +1,22 @@ +import type ExtractorCodec from '../format/ExtractorCodec.js'; +import type { ExtractorMessage, Locale } from '../types.js'; +export default class CatalogPersister { + private messagesPath; + private codec; + private extension; + private sourceLocale; + constructor(params: { + messagesPath: string; + codec: ExtractorCodec; + extension: string; + sourceLocale: Locale; + }); + private getFileName; + private getFilePath; + read(locale: Locale): Promise>; + write(messages: Array, context: { + locale: Locale; + sourceMessagesById: Map; + }): Promise; + getLastModified(locale: Locale): Promise; +} diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/SaveScheduler.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/SaveScheduler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fbae5a3227c4fdb3b9801d1b9eff35a345faeeb --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/catalog/SaveScheduler.d.ts @@ -0,0 +1,18 @@ +type SaveTask = () => Promise; +/** + * De-duplicates excessive save invocations, + * while keeping a single one instant. + */ +export default class SaveScheduler implements Disposable { + private saveTimeout?; + private isSaving; + private delayMs; + private pendingResolvers; + private nextSaveTask?; + constructor(delayMs?: number); + schedule(saveTask: SaveTask): Promise; + private scheduleSave; + private executeSave; + [Symbol.dispose](): void; +} +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/extractMessages.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/extractMessages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea959869792d62a7d7290c7c68fdaa2c20878c12 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/extractMessages.d.ts @@ -0,0 +1,2 @@ +import type { ExtractorConfigInput } from './types.js'; +export default function extractMessages(params: ExtractorConfigInput): Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/LRUCache.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/LRUCache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f81a6b23114ca7b02f93a3b72ec72aaefa525fb5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/LRUCache.d.ts @@ -0,0 +1,7 @@ +export default class LRUCache { + private readonly maxSize; + private cache; + constructor(maxSize: number); + set(key: string, value: Value): void; + get(key: string): Value | undefined; +} diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/MessageExtractor.bench.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/MessageExtractor.bench.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/MessageExtractor.bench.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/MessageExtractor.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/MessageExtractor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40e0cb182e8902ec1a2e08bd2eb2b0b7c461f0ed --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/extractor/MessageExtractor.d.ts @@ -0,0 +1,17 @@ +import type { SourceExtractedMessage } from '../types.js'; +export default class MessageExtractor { + private isDevelopment; + private projectRoot; + private sourceMap; + private compileCache; + constructor(opts: { + isDevelopment?: boolean; + projectRoot?: string; + sourceMap?: boolean; + }); + extract(absoluteFilePath: string, source: string): Promise<{ + messages: Array; + code: string; + map?: string; + }>; +} diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/format/ExtractorCodec.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/format/ExtractorCodec.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..553d064b8add765153f3836275a3adcfe631385a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/format/ExtractorCodec.d.ts @@ -0,0 +1,17 @@ +import type { defineCodec as sharedDefineCodec } from '@eloqnt/config'; +import type { Locale } from '../types.js'; +type SeparateFileCodec = Extract>, { + decode: unknown; +}>; +export default interface ExtractorCodec extends SeparateFileCodec { + /** + * @deprecated No longer used. Catalogs are loaded into your application via + * `decode`, so you can remove `toJSONString` from your codec. Providing it + * logs a deprecation warning and has no effect. + */ + toJSONString?(content: string, context: { + locale: Locale; + }): string; +} +export declare function defineCodec(factory: () => ExtractorCodec): () => ExtractorCodec; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/BuiltInPoCodec.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/BuiltInPoCodec.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e548af551fd3f19ec95dde7f7a0b6cb6cf77122f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/BuiltInPoCodec.d.ts @@ -0,0 +1,2 @@ +declare const _default: () => import("../ExtractorCodec.js").default; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/fixtures/JSONCodecStructured.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/fixtures/JSONCodecStructured.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..69bb31c4542f0217e782d547a1b45e4eaa7df6c4 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/fixtures/JSONCodecStructured.d.ts @@ -0,0 +1,2 @@ +declare const _default: () => import("../../ExtractorCodec.js").default; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/fixtures/POCodecLegacy.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/fixtures/POCodecLegacy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7239da9ce1f5d0845c85103632739b3a3e7ca3db --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/format/codecs/fixtures/POCodecLegacy.d.ts @@ -0,0 +1,52 @@ +declare const _default: () => { + encode(messages: { + [key: string]: unknown; + id: string; + message: string; + description: Array; + references: Array<{ + path: string; + line?: number; + column?: number; + }>; + segments?: Array; + verbatim?: { + value: unknown; + }; + orphan?: boolean; + }[], context: { + locale: string; + sourceMessagesById: Map; + references: Array<{ + path: string; + line?: number; + column?: number; + }>; + segments?: Array; + verbatim?: { + value: unknown; + }; + orphan?: boolean; + }>; + }): string; + decode(content: string, context: { + locale: string; + sourceLocale: string; + }): { + formatPoEmptySource?: string | undefined; + formatPoContext?: string | undefined; + id: string; + message: string; + description: string[]; + references: { + path: string; + line?: number; + }[]; + flags?: Array; + }[]; +}; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/format/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/format/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..47cc4ff1774e5aa7dfbf01662cefd11041bc72c7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/format/index.d.ts @@ -0,0 +1,15 @@ +import type ExtractorCodec from './ExtractorCodec.js'; +import type { MessagesFormat } from './types.js'; +declare const formats: { + json: { + codec: () => Promise; + extension: ".json"; + }; + po: { + codec: () => Promise; + extension: ".po"; + }; +}; +export default formats; +export declare function getFormatExtension(format: MessagesFormat): string; +export declare function resolveCodec(format: MessagesFormat, projectRoot: string): Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/format/types.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/format/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2baf088dd7563b486ebb4a332ba74fc5a6c5653d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/format/types.d.ts @@ -0,0 +1,8 @@ +import type formats from './index.js'; +export type BuiltInMessagesFormat = keyof typeof formats; +type CustomMessagesFormat = { + codec: string; + extension: `.${string}`; +}; +export type MessagesFormat = BuiltInMessagesFormat | CustomMessagesFormat; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..808a883bf50acb707985873859d7c190355c30d4 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/index.d.ts @@ -0,0 +1,2 @@ +export { default as unstable_extractMessages } from './extractMessages.js'; +export { defineCodec } from './format/ExtractorCodec.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/normalizeExtractorConfig.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/normalizeExtractorConfig.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c91f508ed566691f5f8f07952275e6c45e89976 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/normalizeExtractorConfig.d.ts @@ -0,0 +1,5 @@ +import type { ExtractorConfig, ExtractorConfigInput } from './types.js'; +export declare function normalizeMessagesCatalogPaths(messagesPath: string | Array): Array; +export default function normalizeExtractorConfig(input: Omit & { + messages?: ExtractorConfigInput['messages']; +}): ExtractorConfig; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileFilter.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileFilter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..812e85fe95f71b6836b3c742db6661039d6c4e75 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileFilter.d.ts @@ -0,0 +1,8 @@ +export default class SourceFileFilter { + static readonly EXTENSIONS: string[]; + static readonly IGNORED_DIRECTORIES: string[]; + static isSourceFile(filePath: string): boolean; + static shouldEnterDirectory(dirPath: string, srcPaths: Array): boolean; + private static isIgnoredDirectoryExplicitlyIncluded; + static isWithinPath(targetPath: string, basePath: string): boolean; +} diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileScanner.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileScanner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40e57029fa0bcc791f528392eefda6492725c0ec --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileScanner.d.ts @@ -0,0 +1,4 @@ +export default class SourceFileScanner { + private static walkSourceFiles; + static getSourceFiles(srcPaths: Array): Promise>; +} diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileWatcher.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileWatcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d821cc80a9c70ef07b347b1399337723f937ff8 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/source/SourceFileWatcher.d.ts @@ -0,0 +1,15 @@ +import { type Event } from '@parcel/watcher'; +type OnChange = (events: Array) => Promise; +export type SourceFileWatcherEvent = Event; +export default class SourceFileWatcher implements Disposable { + private subscriptions; + private roots; + private onChange; + constructor(roots: Array, onChange: OnChange); + start(): Promise; + private normalizeEvents; + expandDirectoryDeleteEvents(events: Array, prevKnownFiles: Array): Promise>; + stop(): Promise; + [Symbol.dispose](): void; +} +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/types.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3c715ad462b04bda4732949830c5bb5e8bdd7fa --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/types.d.ts @@ -0,0 +1,67 @@ +import type { defineCodec } from '@eloqnt/config'; +import type { MessagesFormat } from './format/types.js'; +export type Locale = string; +type SharedSeparateFileCodec = Extract>, { + decode: unknown; +}>; +export type ExtractorMessageReference = ExtractorMessage['references'][number]; +/** A single statically extracted source-code usage before any aggregation. */ +export type SourceExtractedMessage = { + id: string; + message: string; + description: string | null; + reference: ExtractorMessageReference; +}; +/** An aggregated message that can be read from or written to a catalog. */ +export type ExtractorMessage = ReturnType[number]; +/** + * External extractor configuration (Next.js plugin, `extractMessages`). + */ +export type ExtractorConfigInput = { + /** + * Relative path(s) to your source code files. + */ + srcPath?: string | Array; + messages: { + /** The format of your messages files. */ + format: MessagesFormat; + /** Relative path(s) to your messages files. */ + path: string | Array; + /** + * Locales kept in sync with [`messages.sourceLocale`](https://next-intl.dev/docs/usage/plugin#messages-source-locale). + */ + locales: 'infer' | ReadonlyArray; + /** Locale to which extracted source strings are written. */ + sourceLocale?: string; + }; + /** + * Enables the usage of `useExtracted`. + */ + extract?: true | { + /** Defaults to `messages.path` when it is a single path. */ + path?: string; + /** @deprecated Prefer `messages.sourceLocale`. */ + sourceLocale?: string; + }; +}; +/** Normalized config used internally after `normalizeExtractorConfig`. */ +export type ExtractorConfig = { + extract: { + locales: 'infer' | ReadonlyArray; + path: string; + sourceLocale: string; + srcPath: string | Array; + }; + messages: { + format: MessagesFormat; + path: Array; + }; +}; +export type CatalogLoaderConfig = { + messages: { + format: MessagesFormat; + precompile?: boolean; + sourceLocale: Locale; + }; +}; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/extractor/utils.d.ts b/e-commerce/node_modules/next-intl/dist/types/extractor/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f562701f9ea33aaa2e0787f2d56833dc9c6ba248 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/extractor/utils.d.ts @@ -0,0 +1,9 @@ +import type { ExtractorConfig, ExtractorMessage, ExtractorMessageReference } from './types.js'; +export declare function normalizePathToPosix(filePath: string): string; +export declare function isForbiddenObjectKey(key: string): boolean; +export declare function hasLocalesToExtract(config: Pick): boolean; +export declare function setNestedProperty(obj: Record, keyPath: string, value: any): void; +export declare function warnAboutMissingReferences(messages: Array): void; +export declare function localeCompare(a: string, b: string): number; +export declare function compareReferences(refA: ExtractorMessageReference, refB: ExtractorMessageReference): number; +export declare function getDefaultProjectRoot(): string; diff --git a/e-commerce/node_modules/next-intl/dist/types/index.react-client.d.ts b/e-commerce/node_modules/next-intl/dist/types/index.react-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2396204c968a369281eff7c44858cc30315096e0 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/index.react-client.d.ts @@ -0,0 +1,8 @@ +/** + * This is the default entry file when consumers import from + * 'next-intl'. We use the client APIs in this case. + * + * Note that the `react-server` environment (i.e. RSC) imports + * from `./react-server` instead. + */ +export * from './react-client/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/index.react-server.d.ts b/e-commerce/node_modules/next-intl/dist/types/index.react-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b807403267cc215d6e84a77616d6edc576e78116 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/index.react-server.d.ts @@ -0,0 +1 @@ +export * from './react-server/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/middleware.d.ts b/e-commerce/node_modules/next-intl/dist/types/middleware.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07e4c91c3e83a982a157f46bc561d01d8b42d1dd --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/middleware.d.ts @@ -0,0 +1 @@ +export { default } from './middleware/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/middleware/getAlternateLinksHeaderValue.d.ts b/e-commerce/node_modules/next-intl/dist/types/middleware/getAlternateLinksHeaderValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5f3a0f021afcbf836ba2d803e8099f2c77a82f7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/middleware/getAlternateLinksHeaderValue.d.ts @@ -0,0 +1,13 @@ +import type { NextRequest } from 'next/server.js'; +import type { ResolvedRoutingConfig } from '../routing/config.js'; +import type { DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../routing/types.js'; +/** + * See https://developers.google.com/search/docs/specialty/international/localized-versions + */ +export default function getAlternateLinksHeaderValue | undefined, AppDomains extends DomainsConfig | undefined>({ internalTemplateName, localizedPathnames, request, resolvedLocale, routing }: { + routing: Omit, 'pathnames'>; + request: NextRequest; + resolvedLocale: AppLocales[number]; + localizedPathnames?: Pathnames[string]; + internalTemplateName?: string; +}): string; diff --git a/e-commerce/node_modules/next-intl/dist/types/middleware/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/middleware/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8e82dc9224953e047ab2cf5584225eda83b8d8c --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/middleware/index.d.ts @@ -0,0 +1,4 @@ +/** + * The middleware, available as `next-intl/middleware`. + */ +export { default } from './middleware.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/middleware/middleware.d.ts b/e-commerce/node_modules/next-intl/dist/types/middleware/middleware.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddc5980947106c6c9ff6446ef7e2767b8aabc1a7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/middleware/middleware.d.ts @@ -0,0 +1,4 @@ +import { type NextRequest, NextResponse } from 'next/server.js'; +import { type RoutingConfig } from '../routing/config.js'; +import type { DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../routing/types.js'; +export default function createMiddleware = never, const AppDomains extends DomainsConfig = never>(routing: RoutingConfig): (request: NextRequest) => NextResponse; diff --git a/e-commerce/node_modules/next-intl/dist/types/middleware/resolveLocale.d.ts b/e-commerce/node_modules/next-intl/dist/types/middleware/resolveLocale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..50758156eeecf18643befc2cf7264bcf67aa895a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/middleware/resolveLocale.d.ts @@ -0,0 +1,9 @@ +import type { RequestCookies } from 'next/dist/server/web/spec-extension/cookies.js'; +import type { Locale } from 'use-intl'; +import type { ResolvedRoutingConfig } from '../routing/config.js'; +import type { DomainConfig, DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../routing/types.js'; +export declare function getAcceptLanguageLocale(requestHeaders: Headers, locales: AppLocales, defaultLocale: Locale): string | undefined; +export default function resolveLocale | undefined, AppDomains extends DomainsConfig | undefined>(routing: Omit, 'pathnames'>, requestHeaders: Headers, requestCookies: RequestCookies, pathname: string): { + locale: AppLocales[number]; + domain?: DomainConfig; +}; diff --git a/e-commerce/node_modules/next-intl/dist/types/middleware/syncCookie.d.ts b/e-commerce/node_modules/next-intl/dist/types/middleware/syncCookie.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa405d950cade3853f4b993a5dfca4ca61dd7374 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/middleware/syncCookie.d.ts @@ -0,0 +1,7 @@ +import type { NextRequest, NextResponse } from 'next/server.js'; +import type { Locale } from 'use-intl'; +import type { InitializedLocaleCookieConfig, ResolvedRoutingConfig } from '../routing/config.js'; +import type { DomainConfig, DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../routing/types.js'; +export default function syncCookie | undefined, AppDomains extends DomainsConfig | undefined>(request: NextRequest, response: NextResponse, locale: Locale, routing: Pick, 'locales' | 'defaultLocale'> & { + localeCookie: InitializedLocaleCookieConfig; +}, domain?: DomainConfig): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/middleware/utils.d.ts b/e-commerce/node_modules/next-intl/dist/types/middleware/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f87907d58654a3e1a59a8b52351828a8145d565c --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/middleware/utils.d.ts @@ -0,0 +1,26 @@ +import type { Locale } from 'use-intl'; +import type { DomainConfig, DomainsConfig, LocalePrefixConfigVerbose, LocalePrefixMode, Locales, Pathnames } from '../routing/types.js'; +export declare function getFirstPathnameSegment(pathname: string): string; +export declare function getInternalTemplate>(pathnames: AppPathnames, pathname: string, locale: AppLocales[number]): [AppLocales[number] | undefined, keyof AppPathnames | undefined]; +export declare function formatTemplatePathname(sourcePathname: string, sourceTemplate: string, targetTemplate: string, prefix?: string): string; +/** + * Removes potential prefixes from the pathname. + */ +export declare function getNormalizedPathname(pathname: string, locales: AppLocales, localePrefix: LocalePrefixConfigVerbose): string; +export declare function findCaseInsensitiveString(candidate: string, strings: Array): string | undefined; +export declare function getLocalePrefixes(locales: AppLocales, localePrefix: LocalePrefixConfigVerbose, sort?: boolean): Array<[AppLocales[number], string]>; +export declare function getPathnameMatch(pathname: string, locales: AppLocales, localePrefix: LocalePrefixConfigVerbose, domain?: DomainConfig): { + locale: AppLocales[number]; + prefix: string; + matchedPrefix: string; + exact?: boolean; +} | undefined; +export declare function getRouteParams(template: string, pathname: string): Record | undefined; +export declare function formatPathnameTemplate(template: string, params?: object): string; +export declare function formatPathname(pathname: string, prefix: string | undefined, search: string | undefined): string; +export declare function getHost(requestHeaders: Headers): string | undefined; +export declare function isLocaleSupportedOnDomain(locale: Locale, domain: DomainConfig): boolean; +export declare function getBestMatchingDomain(curHostDomain: DomainConfig | undefined, locale: Locale, domainsConfig: DomainsConfig): DomainConfig | undefined; +export declare function applyBasePath(pathname: string, basePath: string): string; +export declare function getLocaleAsPrefix(locale: AppLocales[number]): string; +export declare function sanitizePathname(pathname: string): string; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation.react-client.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation.react-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..690c40fe3f21c666529cf33e0da33f1e6912a89f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation.react-client.d.ts @@ -0,0 +1 @@ +export * from './navigation/react-client/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation.react-server.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation.react-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62fcb6ec373bc39a7819e9058dc13729d9eef510 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation.react-server.d.ts @@ -0,0 +1 @@ +export * from './navigation/react-server/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/createNavigation.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/createNavigation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b4783dcaf67179a2e6ff81323a2cbcd687156c9 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/createNavigation.d.ts @@ -0,0 +1,466 @@ +import { type Locale } from 'use-intl'; +import type { RoutingConfigLocalizedNavigation, RoutingConfigSharedNavigation } from '../../routing/config.js'; +import type { DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../../routing/types.js'; +export default function createNavigation = never, const AppDomains extends DomainsConfig = never>(routing?: [AppPathnames] extends [never] ? RoutingConfigSharedNavigation | undefined : RoutingConfigLocalizedNavigation): { + Link: import("react").ForwardRefExoticComponent | undefined; + prefix?: string | undefined | undefined; + key?: import("react").Key | null | undefined; + as?: (string | import("url").UrlObject) | undefined; + scroll?: boolean | undefined; + shallow?: boolean | undefined; + passHref?: boolean | undefined; + prefetch?: boolean | "auto" | null | undefined; + legacyBehavior?: boolean | undefined; + onNavigate?: ((event: { + preventDefault: () => void; + }) => void) | undefined; + transitionTypes?: string[] | undefined; + download?: any; + hrefLang?: string | undefined | undefined; + media?: string | undefined | undefined; + ping?: string | undefined | undefined; + type?: string | undefined | undefined; + referrerPolicy?: import("react").HTMLAttributeReferrerPolicy | undefined; + defaultChecked?: boolean | undefined | undefined; + defaultValue?: string | number | readonly string[] | undefined; + suppressContentEditableWarning?: boolean | undefined | undefined; + suppressHydrationWarning?: boolean | undefined | undefined; + accessKey?: string | undefined | undefined; + autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | undefined | (string & {}) | undefined; + autoFocus?: boolean | undefined | undefined; + className?: string | undefined | undefined; + contentEditable?: (boolean | "true" | "false") | "inherit" | "plaintext-only" | undefined; + contextMenu?: string | undefined | undefined; + dir?: string | undefined | undefined; + draggable?: (boolean | "true" | "false") | undefined; + enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined | undefined; + hidden?: boolean | undefined | undefined; + lang?: string | undefined | undefined; + nonce?: string | undefined | undefined; + spellCheck?: (boolean | "true" | "false") | undefined; + tabIndex?: number | undefined | undefined; + translate?: "yes" | "no" | undefined | undefined; + radioGroup?: string | undefined | undefined; + role?: import("react").AriaRole | undefined; + about?: string | undefined | undefined; + content?: string | undefined | undefined; + datatype?: string | undefined | undefined; + inlist?: any; + property?: string | undefined | undefined; + rel?: string | undefined | undefined; + resource?: string | undefined | undefined; + rev?: string | undefined | undefined; + typeof?: string | undefined | undefined; + vocab?: string | undefined | undefined; + autoCorrect?: string | undefined | undefined; + autoSave?: string | undefined | undefined; + color?: string | undefined | undefined; + itemProp?: string | undefined | undefined; + itemScope?: boolean | undefined | undefined; + itemType?: string | undefined | undefined; + itemID?: string | undefined | undefined; + itemRef?: string | undefined | undefined; + results?: number | undefined | undefined; + security?: string | undefined | undefined; + unselectable?: "on" | "off" | undefined | undefined; + popover?: "" | "auto" | "manual" | "hint" | undefined | undefined; + popoverTargetAction?: "toggle" | "show" | "hide" | undefined | undefined; + popoverTarget?: string | undefined | undefined; + inert?: boolean | undefined | undefined; + inputMode?: "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined | undefined; + is?: string | undefined | undefined; + exportparts?: string | undefined | undefined; + part?: string | undefined | undefined; + "aria-activedescendant"?: string | undefined | undefined; + "aria-atomic"?: (boolean | "true" | "false") | undefined; + "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined | undefined; + "aria-braillelabel"?: string | undefined | undefined; + "aria-brailleroledescription"?: string | undefined | undefined; + "aria-busy"?: (boolean | "true" | "false") | undefined; + "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined | undefined; + "aria-colcount"?: number | undefined | undefined; + "aria-colindex"?: number | undefined | undefined; + "aria-colindextext"?: string | undefined | undefined; + "aria-colspan"?: number | undefined | undefined; + "aria-controls"?: string | undefined | undefined; + "aria-current"?: boolean | "false" | "true" | "page" | "step" | "location" | "date" | "time" | undefined | undefined; + "aria-describedby"?: string | undefined | undefined; + "aria-description"?: string | undefined | undefined; + "aria-details"?: string | undefined | undefined; + "aria-disabled"?: (boolean | "true" | "false") | undefined; + "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined | undefined; + "aria-errormessage"?: string | undefined | undefined; + "aria-expanded"?: (boolean | "true" | "false") | undefined; + "aria-flowto"?: string | undefined | undefined; + "aria-grabbed"?: (boolean | "true" | "false") | undefined; + "aria-haspopup"?: boolean | "false" | "true" | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined | undefined; + "aria-hidden"?: (boolean | "true" | "false") | undefined; + "aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling" | undefined | undefined; + "aria-keyshortcuts"?: string | undefined | undefined; + "aria-label"?: string | undefined | undefined; + "aria-labelledby"?: string | undefined | undefined; + "aria-level"?: number | undefined | undefined; + "aria-live"?: "off" | "assertive" | "polite" | undefined | undefined; + "aria-modal"?: (boolean | "true" | "false") | undefined; + "aria-multiline"?: (boolean | "true" | "false") | undefined; + "aria-multiselectable"?: (boolean | "true" | "false") | undefined; + "aria-orientation"?: "horizontal" | "vertical" | undefined | undefined; + "aria-owns"?: string | undefined | undefined; + "aria-placeholder"?: string | undefined | undefined; + "aria-posinset"?: number | undefined | undefined; + "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined | undefined; + "aria-readonly"?: (boolean | "true" | "false") | undefined; + "aria-relevant"?: "additions" | "additions removals" | "additions text" | "all" | "removals" | "removals additions" | "removals text" | "text" | "text additions" | "text removals" | undefined | undefined; + "aria-required"?: (boolean | "true" | "false") | undefined; + "aria-roledescription"?: string | undefined | undefined; + "aria-rowcount"?: number | undefined | undefined; + "aria-rowindex"?: number | undefined | undefined; + "aria-rowindextext"?: string | undefined | undefined; + "aria-rowspan"?: number | undefined | undefined; + "aria-selected"?: (boolean | "true" | "false") | undefined; + "aria-setsize"?: number | undefined | undefined; + "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined | undefined; + "aria-valuemax"?: number | undefined | undefined; + "aria-valuemin"?: number | undefined | undefined; + "aria-valuenow"?: number | undefined | undefined; + "aria-valuetext"?: string | undefined | undefined; + href: [AppPathnames] extends [never] ? string | import("url").UrlObject : keyof AppPathnames extends infer T ? T extends keyof AppPathnames ? T extends `${string}[[...${string}` ? T | ({ + pathname: T; + params?: import("../shared/StrictParams.js").default | undefined; + } & Omit) : T extends `${string}[${string}` ? { + pathname: T; + params: import("../shared/StrictParams.js").default; + } & Omit : T | ({ + pathname: T; + } & Omit) : never : never; + children?: import("react").ReactNode; + dangerouslySetInnerHTML?: { + __html: string | TrustedHTML; + } | undefined | undefined; + onCopy?: import("react").ClipboardEventHandler | undefined; + onCopyCapture?: import("react").ClipboardEventHandler | undefined; + onCut?: import("react").ClipboardEventHandler | undefined; + onCutCapture?: import("react").ClipboardEventHandler | undefined; + onPaste?: import("react").ClipboardEventHandler | undefined; + onPasteCapture?: import("react").ClipboardEventHandler | undefined; + onCompositionEnd?: import("react").CompositionEventHandler | undefined; + onCompositionEndCapture?: import("react").CompositionEventHandler | undefined; + onCompositionStart?: import("react").CompositionEventHandler | undefined; + onCompositionStartCapture?: import("react").CompositionEventHandler | undefined; + onCompositionUpdate?: import("react").CompositionEventHandler | undefined; + onCompositionUpdateCapture?: import("react").CompositionEventHandler | undefined; + onFocus?: import("react").FocusEventHandler | undefined; + onFocusCapture?: import("react").FocusEventHandler | undefined; + onBlur?: import("react").FocusEventHandler | undefined; + onBlurCapture?: import("react").FocusEventHandler | undefined; + onChange?: import("react").ChangeEventHandler | undefined; + onChangeCapture?: import("react").ChangeEventHandler | undefined; + onBeforeInput?: import("react").InputEventHandler | undefined; + onBeforeInputCapture?: import("react").InputEventHandler | undefined; + onInput?: import("react").InputEventHandler | undefined; + onInputCapture?: import("react").InputEventHandler | undefined; + onReset?: import("react").ReactEventHandler | undefined; + onResetCapture?: import("react").ReactEventHandler | undefined; + onSubmit?: import("react").SubmitEventHandler | undefined; + onSubmitCapture?: import("react").SubmitEventHandler | undefined; + onInvalid?: import("react").ReactEventHandler | undefined; + onInvalidCapture?: import("react").ReactEventHandler | undefined; + onLoad?: import("react").ReactEventHandler | undefined; + onLoadCapture?: import("react").ReactEventHandler | undefined; + onError?: import("react").ReactEventHandler | undefined; + onErrorCapture?: import("react").ReactEventHandler | undefined; + onKeyDown?: import("react").KeyboardEventHandler | undefined; + onKeyDownCapture?: import("react").KeyboardEventHandler | undefined; + onKeyPress?: import("react").KeyboardEventHandler | undefined; + onKeyPressCapture?: import("react").KeyboardEventHandler | undefined; + onKeyUp?: import("react").KeyboardEventHandler | undefined; + onKeyUpCapture?: import("react").KeyboardEventHandler | undefined; + onAbort?: import("react").ReactEventHandler | undefined; + onAbortCapture?: import("react").ReactEventHandler | undefined; + onCanPlay?: import("react").ReactEventHandler | undefined; + onCanPlayCapture?: import("react").ReactEventHandler | undefined; + onCanPlayThrough?: import("react").ReactEventHandler | undefined; + onCanPlayThroughCapture?: import("react").ReactEventHandler | undefined; + onDurationChange?: import("react").ReactEventHandler | undefined; + onDurationChangeCapture?: import("react").ReactEventHandler | undefined; + onEmptied?: import("react").ReactEventHandler | undefined; + onEmptiedCapture?: import("react").ReactEventHandler | undefined; + onEncrypted?: import("react").ReactEventHandler | undefined; + onEncryptedCapture?: import("react").ReactEventHandler | undefined; + onEnded?: import("react").ReactEventHandler | undefined; + onEndedCapture?: import("react").ReactEventHandler | undefined; + onLoadedData?: import("react").ReactEventHandler | undefined; + onLoadedDataCapture?: import("react").ReactEventHandler | undefined; + onLoadedMetadata?: import("react").ReactEventHandler | undefined; + onLoadedMetadataCapture?: import("react").ReactEventHandler | undefined; + onLoadStart?: import("react").ReactEventHandler | undefined; + onLoadStartCapture?: import("react").ReactEventHandler | undefined; + onPause?: import("react").ReactEventHandler | undefined; + onPauseCapture?: import("react").ReactEventHandler | undefined; + onPlay?: import("react").ReactEventHandler | undefined; + onPlayCapture?: import("react").ReactEventHandler | undefined; + onPlaying?: import("react").ReactEventHandler | undefined; + onPlayingCapture?: import("react").ReactEventHandler | undefined; + onProgress?: import("react").ReactEventHandler | undefined; + onProgressCapture?: import("react").ReactEventHandler | undefined; + onRateChange?: import("react").ReactEventHandler | undefined; + onRateChangeCapture?: import("react").ReactEventHandler | undefined; + onSeeked?: import("react").ReactEventHandler | undefined; + onSeekedCapture?: import("react").ReactEventHandler | undefined; + onSeeking?: import("react").ReactEventHandler | undefined; + onSeekingCapture?: import("react").ReactEventHandler | undefined; + onStalled?: import("react").ReactEventHandler | undefined; + onStalledCapture?: import("react").ReactEventHandler | undefined; + onSuspend?: import("react").ReactEventHandler | undefined; + onSuspendCapture?: import("react").ReactEventHandler | undefined; + onTimeUpdate?: import("react").ReactEventHandler | undefined; + onTimeUpdateCapture?: import("react").ReactEventHandler | undefined; + onVolumeChange?: import("react").ReactEventHandler | undefined; + onVolumeChangeCapture?: import("react").ReactEventHandler | undefined; + onWaiting?: import("react").ReactEventHandler | undefined; + onWaitingCapture?: import("react").ReactEventHandler | undefined; + onAuxClick?: import("react").MouseEventHandler | undefined; + onAuxClickCapture?: import("react").MouseEventHandler | undefined; + onClick?: import("react").MouseEventHandler | undefined; + onClickCapture?: import("react").MouseEventHandler | undefined; + onContextMenu?: import("react").MouseEventHandler | undefined; + onContextMenuCapture?: import("react").MouseEventHandler | undefined; + onDoubleClick?: import("react").MouseEventHandler | undefined; + onDoubleClickCapture?: import("react").MouseEventHandler | undefined; + onDrag?: import("react").DragEventHandler | undefined; + onDragCapture?: import("react").DragEventHandler | undefined; + onDragEnd?: import("react").DragEventHandler | undefined; + onDragEndCapture?: import("react").DragEventHandler | undefined; + onDragEnter?: import("react").DragEventHandler | undefined; + onDragEnterCapture?: import("react").DragEventHandler | undefined; + onDragExit?: import("react").DragEventHandler | undefined; + onDragExitCapture?: import("react").DragEventHandler | undefined; + onDragLeave?: import("react").DragEventHandler | undefined; + onDragLeaveCapture?: import("react").DragEventHandler | undefined; + onDragOver?: import("react").DragEventHandler | undefined; + onDragOverCapture?: import("react").DragEventHandler | undefined; + onDragStart?: import("react").DragEventHandler | undefined; + onDragStartCapture?: import("react").DragEventHandler | undefined; + onDrop?: import("react").DragEventHandler | undefined; + onDropCapture?: import("react").DragEventHandler | undefined; + onMouseDown?: import("react").MouseEventHandler | undefined; + onMouseDownCapture?: import("react").MouseEventHandler | undefined; + onMouseEnter?: import("react").MouseEventHandler | undefined; + onMouseLeave?: import("react").MouseEventHandler | undefined; + onMouseMove?: import("react").MouseEventHandler | undefined; + onMouseMoveCapture?: import("react").MouseEventHandler | undefined; + onMouseOut?: import("react").MouseEventHandler | undefined; + onMouseOutCapture?: import("react").MouseEventHandler | undefined; + onMouseOver?: import("react").MouseEventHandler | undefined; + onMouseOverCapture?: import("react").MouseEventHandler | undefined; + onMouseUp?: import("react").MouseEventHandler | undefined; + onMouseUpCapture?: import("react").MouseEventHandler | undefined; + onSelect?: import("react").ReactEventHandler | undefined; + onSelectCapture?: import("react").ReactEventHandler | undefined; + onTouchCancel?: import("react").TouchEventHandler | undefined; + onTouchCancelCapture?: import("react").TouchEventHandler | undefined; + onTouchEnd?: import("react").TouchEventHandler | undefined; + onTouchEndCapture?: import("react").TouchEventHandler | undefined; + onTouchMove?: import("react").TouchEventHandler | undefined; + onTouchMoveCapture?: import("react").TouchEventHandler | undefined; + onTouchStart?: import("react").TouchEventHandler | undefined; + onTouchStartCapture?: import("react").TouchEventHandler | undefined; + onPointerDown?: import("react").PointerEventHandler | undefined; + onPointerDownCapture?: import("react").PointerEventHandler | undefined; + onPointerMove?: import("react").PointerEventHandler | undefined; + onPointerMoveCapture?: import("react").PointerEventHandler | undefined; + onPointerUp?: import("react").PointerEventHandler | undefined; + onPointerUpCapture?: import("react").PointerEventHandler | undefined; + onPointerCancel?: import("react").PointerEventHandler | undefined; + onPointerCancelCapture?: import("react").PointerEventHandler | undefined; + onPointerEnter?: import("react").PointerEventHandler | undefined; + onPointerLeave?: import("react").PointerEventHandler | undefined; + onPointerOver?: import("react").PointerEventHandler | undefined; + onPointerOverCapture?: import("react").PointerEventHandler | undefined; + onPointerOut?: import("react").PointerEventHandler | undefined; + onPointerOutCapture?: import("react").PointerEventHandler | undefined; + onGotPointerCapture?: import("react").PointerEventHandler | undefined; + onGotPointerCaptureCapture?: import("react").PointerEventHandler | undefined; + onLostPointerCapture?: import("react").PointerEventHandler | undefined; + onLostPointerCaptureCapture?: import("react").PointerEventHandler | undefined; + onScroll?: import("react").UIEventHandler | undefined; + onScrollCapture?: import("react").UIEventHandler | undefined; + onScrollEnd?: import("react").UIEventHandler | undefined; + onScrollEndCapture?: import("react").UIEventHandler | undefined; + onWheel?: import("react").WheelEventHandler | undefined; + onWheelCapture?: import("react").WheelEventHandler | undefined; + onAnimationStart?: import("react").AnimationEventHandler | undefined; + onAnimationStartCapture?: import("react").AnimationEventHandler | undefined; + onAnimationEnd?: import("react").AnimationEventHandler | undefined; + onAnimationEndCapture?: import("react").AnimationEventHandler | undefined; + onAnimationIteration?: import("react").AnimationEventHandler | undefined; + onAnimationIterationCapture?: import("react").AnimationEventHandler | undefined; + onToggle?: import("react").ToggleEventHandler | undefined; + onBeforeToggle?: import("react").ToggleEventHandler | undefined; + onTransitionCancel?: import("react").TransitionEventHandler | undefined; + onTransitionCancelCapture?: import("react").TransitionEventHandler | undefined; + onTransitionEnd?: import("react").TransitionEventHandler | undefined; + onTransitionEndCapture?: import("react").TransitionEventHandler | undefined; + onTransitionRun?: import("react").TransitionEventHandler | undefined; + onTransitionRunCapture?: import("react").TransitionEventHandler | undefined; + onTransitionStart?: import("react").TransitionEventHandler | undefined; + onTransitionStartCapture?: import("react").TransitionEventHandler | undefined; + }, "ref"> & import("react").RefAttributes>; + usePathname: () => [AppPathnames] extends [never] ? string : keyof AppPathnames; + useRouter: () => { + /** @see https://next-intl.dev/docs/routing/navigation#userouter */ + push: (href: Parameters<(args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: Locale; + forcePrefix?: boolean; + }) => string>[0]["href"], options?: (Partial & { + locale?: Locale; + }) | undefined) => void; + /** @see https://next-intl.dev/docs/routing/navigation#userouter */ + replace: (href: Parameters<(args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: Locale; + forcePrefix?: boolean; + }) => string>[0]["href"], options?: (Partial & { + locale?: Locale; + }) | undefined) => void; + /** @see https://next-intl.dev/docs/routing/navigation#userouter */ + prefetch: (href: Parameters<(args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: Locale; + forcePrefix?: boolean; + }) => string>[0]["href"], options?: (Partial & { + locale?: Locale; + }) | undefined) => void; + back(): void; + forward(): void; + refresh(): void; + experimental_gesturePush?(href: string, options?: import("next/dist/shared/lib/app-router-context.shared-runtime.js").NavigateOptions): void; + bfcacheId: string; + }; + getPathname: (args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: Locale; + forcePrefix?: boolean; + }) => string; + redirect: (args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: Locale; + forcePrefix?: boolean; + }, type?: import("next/dist/client/components/redirect-error.js").RedirectType | undefined) => never; + permanentRedirect: (args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: Locale; + forcePrefix?: boolean; + }, type?: import("next/dist/client/components/redirect-error.js").RedirectType | undefined) => never; +}; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0f3c0f4ae86f7abb5b29f3fe9e296c96bb21829 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/index.d.ts @@ -0,0 +1,2 @@ +export { default as createNavigation } from './createNavigation.js'; +export type { QueryParams } from '../shared/utils.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/useBasePathname.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/useBasePathname.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ded7c58fc0372aeff02813d2bce353b1aec78d5a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/react-client/useBasePathname.d.ts @@ -0,0 +1,5 @@ +import type { LocalePrefixConfigVerbose, LocalePrefixMode, Locales } from '../../routing/types.js'; +export default function useBasePathname(config: { + localePrefix: LocalePrefixConfigVerbose; + defaultLocale?: AppLocales[number]; +}): string | null; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/createNavigation.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/createNavigation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8322271f9249fef1c395f77620cbca178b46ecf9 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/createNavigation.d.ts @@ -0,0 +1,384 @@ +import type { RoutingConfigLocalizedNavigation, RoutingConfigSharedNavigation } from '../../routing/config.js'; +import type { DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../../routing/types.js'; +export default function createNavigation = never, const AppDomains extends DomainsConfig = never>(routing?: [AppPathnames] extends [never] ? RoutingConfigSharedNavigation | undefined : RoutingConfigLocalizedNavigation): { + usePathname: () => never; + useRouter: () => never; + Link: import("react").ForwardRefExoticComponent | undefined; + prefix?: string | undefined | undefined; + key?: import("react").Key | null | undefined; + as?: (string | import("url").UrlObject) | undefined; + scroll?: boolean | undefined; + shallow?: boolean | undefined; + passHref?: boolean | undefined; + prefetch?: boolean | "auto" | null | undefined; + legacyBehavior?: boolean | undefined; + onNavigate?: ((event: { + preventDefault: () => void; + }) => void) | undefined; + transitionTypes?: string[] | undefined; + download?: any; + hrefLang?: string | undefined | undefined; + media?: string | undefined | undefined; + ping?: string | undefined | undefined; + type?: string | undefined | undefined; + referrerPolicy?: import("react").HTMLAttributeReferrerPolicy | undefined; + defaultChecked?: boolean | undefined | undefined; + defaultValue?: string | number | readonly string[] | undefined; + suppressContentEditableWarning?: boolean | undefined | undefined; + suppressHydrationWarning?: boolean | undefined | undefined; + accessKey?: string | undefined | undefined; + autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | undefined | (string & {}) | undefined; + autoFocus?: boolean | undefined | undefined; + className?: string | undefined | undefined; + contentEditable?: (boolean | "true" | "false") | "inherit" | "plaintext-only" | undefined; + contextMenu?: string | undefined | undefined; + dir?: string | undefined | undefined; + draggable?: (boolean | "true" | "false") | undefined; + enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined | undefined; + hidden?: boolean | undefined | undefined; + lang?: string | undefined | undefined; + nonce?: string | undefined | undefined; + spellCheck?: (boolean | "true" | "false") | undefined; + tabIndex?: number | undefined | undefined; + translate?: "yes" | "no" | undefined | undefined; + radioGroup?: string | undefined | undefined; + role?: import("react").AriaRole | undefined; + about?: string | undefined | undefined; + content?: string | undefined | undefined; + datatype?: string | undefined | undefined; + inlist?: any; + property?: string | undefined | undefined; + rel?: string | undefined | undefined; + resource?: string | undefined | undefined; + rev?: string | undefined | undefined; + typeof?: string | undefined | undefined; + vocab?: string | undefined | undefined; + autoCorrect?: string | undefined | undefined; + autoSave?: string | undefined | undefined; + color?: string | undefined | undefined; + itemProp?: string | undefined | undefined; + itemScope?: boolean | undefined | undefined; + itemType?: string | undefined | undefined; + itemID?: string | undefined | undefined; + itemRef?: string | undefined | undefined; + results?: number | undefined | undefined; + security?: string | undefined | undefined; + unselectable?: "on" | "off" | undefined | undefined; + popover?: "" | "auto" | "manual" | "hint" | undefined | undefined; + popoverTargetAction?: "toggle" | "show" | "hide" | undefined | undefined; + popoverTarget?: string | undefined | undefined; + inert?: boolean | undefined | undefined; + inputMode?: "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined | undefined; + is?: string | undefined | undefined; + exportparts?: string | undefined | undefined; + part?: string | undefined | undefined; + "aria-activedescendant"?: string | undefined | undefined; + "aria-atomic"?: (boolean | "true" | "false") | undefined; + "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined | undefined; + "aria-braillelabel"?: string | undefined | undefined; + "aria-brailleroledescription"?: string | undefined | undefined; + "aria-busy"?: (boolean | "true" | "false") | undefined; + "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined | undefined; + "aria-colcount"?: number | undefined | undefined; + "aria-colindex"?: number | undefined | undefined; + "aria-colindextext"?: string | undefined | undefined; + "aria-colspan"?: number | undefined | undefined; + "aria-controls"?: string | undefined | undefined; + "aria-current"?: boolean | "false" | "true" | "page" | "step" | "location" | "date" | "time" | undefined | undefined; + "aria-describedby"?: string | undefined | undefined; + "aria-description"?: string | undefined | undefined; + "aria-details"?: string | undefined | undefined; + "aria-disabled"?: (boolean | "true" | "false") | undefined; + "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined | undefined; + "aria-errormessage"?: string | undefined | undefined; + "aria-expanded"?: (boolean | "true" | "false") | undefined; + "aria-flowto"?: string | undefined | undefined; + "aria-grabbed"?: (boolean | "true" | "false") | undefined; + "aria-haspopup"?: boolean | "false" | "true" | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined | undefined; + "aria-hidden"?: (boolean | "true" | "false") | undefined; + "aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling" | undefined | undefined; + "aria-keyshortcuts"?: string | undefined | undefined; + "aria-label"?: string | undefined | undefined; + "aria-labelledby"?: string | undefined | undefined; + "aria-level"?: number | undefined | undefined; + "aria-live"?: "off" | "assertive" | "polite" | undefined | undefined; + "aria-modal"?: (boolean | "true" | "false") | undefined; + "aria-multiline"?: (boolean | "true" | "false") | undefined; + "aria-multiselectable"?: (boolean | "true" | "false") | undefined; + "aria-orientation"?: "horizontal" | "vertical" | undefined | undefined; + "aria-owns"?: string | undefined | undefined; + "aria-placeholder"?: string | undefined | undefined; + "aria-posinset"?: number | undefined | undefined; + "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined | undefined; + "aria-readonly"?: (boolean | "true" | "false") | undefined; + "aria-relevant"?: "additions" | "additions removals" | "additions text" | "all" | "removals" | "removals additions" | "removals text" | "text" | "text additions" | "text removals" | undefined | undefined; + "aria-required"?: (boolean | "true" | "false") | undefined; + "aria-roledescription"?: string | undefined | undefined; + "aria-rowcount"?: number | undefined | undefined; + "aria-rowindex"?: number | undefined | undefined; + "aria-rowindextext"?: string | undefined | undefined; + "aria-rowspan"?: number | undefined | undefined; + "aria-selected"?: (boolean | "true" | "false") | undefined; + "aria-setsize"?: number | undefined | undefined; + "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined | undefined; + "aria-valuemax"?: number | undefined | undefined; + "aria-valuemin"?: number | undefined | undefined; + "aria-valuenow"?: number | undefined | undefined; + "aria-valuetext"?: string | undefined | undefined; + href: [AppPathnames] extends [never] ? string | import("url").UrlObject : keyof AppPathnames extends infer T ? T extends keyof AppPathnames ? T extends `${string}[[...${string}` ? T | ({ + pathname: T; + params?: import("../shared/StrictParams.js").default | undefined; + } & Omit) : T extends `${string}[${string}` ? { + pathname: T; + params: import("../shared/StrictParams.js").default; + } & Omit : T | ({ + pathname: T; + } & Omit) : never : never; + children?: import("react").ReactNode; + dangerouslySetInnerHTML?: { + __html: string | TrustedHTML; + } | undefined | undefined; + onCopy?: import("react").ClipboardEventHandler | undefined; + onCopyCapture?: import("react").ClipboardEventHandler | undefined; + onCut?: import("react").ClipboardEventHandler | undefined; + onCutCapture?: import("react").ClipboardEventHandler | undefined; + onPaste?: import("react").ClipboardEventHandler | undefined; + onPasteCapture?: import("react").ClipboardEventHandler | undefined; + onCompositionEnd?: import("react").CompositionEventHandler | undefined; + onCompositionEndCapture?: import("react").CompositionEventHandler | undefined; + onCompositionStart?: import("react").CompositionEventHandler | undefined; + onCompositionStartCapture?: import("react").CompositionEventHandler | undefined; + onCompositionUpdate?: import("react").CompositionEventHandler | undefined; + onCompositionUpdateCapture?: import("react").CompositionEventHandler | undefined; + onFocus?: import("react").FocusEventHandler | undefined; + onFocusCapture?: import("react").FocusEventHandler | undefined; + onBlur?: import("react").FocusEventHandler | undefined; + onBlurCapture?: import("react").FocusEventHandler | undefined; + onChange?: import("react").ChangeEventHandler | undefined; + onChangeCapture?: import("react").ChangeEventHandler | undefined; + onBeforeInput?: import("react").InputEventHandler | undefined; + onBeforeInputCapture?: import("react").InputEventHandler | undefined; + onInput?: import("react").InputEventHandler | undefined; + onInputCapture?: import("react").InputEventHandler | undefined; + onReset?: import("react").ReactEventHandler | undefined; + onResetCapture?: import("react").ReactEventHandler | undefined; + onSubmit?: import("react").SubmitEventHandler | undefined; + onSubmitCapture?: import("react").SubmitEventHandler | undefined; + onInvalid?: import("react").ReactEventHandler | undefined; + onInvalidCapture?: import("react").ReactEventHandler | undefined; + onLoad?: import("react").ReactEventHandler | undefined; + onLoadCapture?: import("react").ReactEventHandler | undefined; + onError?: import("react").ReactEventHandler | undefined; + onErrorCapture?: import("react").ReactEventHandler | undefined; + onKeyDown?: import("react").KeyboardEventHandler | undefined; + onKeyDownCapture?: import("react").KeyboardEventHandler | undefined; + onKeyPress?: import("react").KeyboardEventHandler | undefined; + onKeyPressCapture?: import("react").KeyboardEventHandler | undefined; + onKeyUp?: import("react").KeyboardEventHandler | undefined; + onKeyUpCapture?: import("react").KeyboardEventHandler | undefined; + onAbort?: import("react").ReactEventHandler | undefined; + onAbortCapture?: import("react").ReactEventHandler | undefined; + onCanPlay?: import("react").ReactEventHandler | undefined; + onCanPlayCapture?: import("react").ReactEventHandler | undefined; + onCanPlayThrough?: import("react").ReactEventHandler | undefined; + onCanPlayThroughCapture?: import("react").ReactEventHandler | undefined; + onDurationChange?: import("react").ReactEventHandler | undefined; + onDurationChangeCapture?: import("react").ReactEventHandler | undefined; + onEmptied?: import("react").ReactEventHandler | undefined; + onEmptiedCapture?: import("react").ReactEventHandler | undefined; + onEncrypted?: import("react").ReactEventHandler | undefined; + onEncryptedCapture?: import("react").ReactEventHandler | undefined; + onEnded?: import("react").ReactEventHandler | undefined; + onEndedCapture?: import("react").ReactEventHandler | undefined; + onLoadedData?: import("react").ReactEventHandler | undefined; + onLoadedDataCapture?: import("react").ReactEventHandler | undefined; + onLoadedMetadata?: import("react").ReactEventHandler | undefined; + onLoadedMetadataCapture?: import("react").ReactEventHandler | undefined; + onLoadStart?: import("react").ReactEventHandler | undefined; + onLoadStartCapture?: import("react").ReactEventHandler | undefined; + onPause?: import("react").ReactEventHandler | undefined; + onPauseCapture?: import("react").ReactEventHandler | undefined; + onPlay?: import("react").ReactEventHandler | undefined; + onPlayCapture?: import("react").ReactEventHandler | undefined; + onPlaying?: import("react").ReactEventHandler | undefined; + onPlayingCapture?: import("react").ReactEventHandler | undefined; + onProgress?: import("react").ReactEventHandler | undefined; + onProgressCapture?: import("react").ReactEventHandler | undefined; + onRateChange?: import("react").ReactEventHandler | undefined; + onRateChangeCapture?: import("react").ReactEventHandler | undefined; + onSeeked?: import("react").ReactEventHandler | undefined; + onSeekedCapture?: import("react").ReactEventHandler | undefined; + onSeeking?: import("react").ReactEventHandler | undefined; + onSeekingCapture?: import("react").ReactEventHandler | undefined; + onStalled?: import("react").ReactEventHandler | undefined; + onStalledCapture?: import("react").ReactEventHandler | undefined; + onSuspend?: import("react").ReactEventHandler | undefined; + onSuspendCapture?: import("react").ReactEventHandler | undefined; + onTimeUpdate?: import("react").ReactEventHandler | undefined; + onTimeUpdateCapture?: import("react").ReactEventHandler | undefined; + onVolumeChange?: import("react").ReactEventHandler | undefined; + onVolumeChangeCapture?: import("react").ReactEventHandler | undefined; + onWaiting?: import("react").ReactEventHandler | undefined; + onWaitingCapture?: import("react").ReactEventHandler | undefined; + onAuxClick?: import("react").MouseEventHandler | undefined; + onAuxClickCapture?: import("react").MouseEventHandler | undefined; + onClick?: import("react").MouseEventHandler | undefined; + onClickCapture?: import("react").MouseEventHandler | undefined; + onContextMenu?: import("react").MouseEventHandler | undefined; + onContextMenuCapture?: import("react").MouseEventHandler | undefined; + onDoubleClick?: import("react").MouseEventHandler | undefined; + onDoubleClickCapture?: import("react").MouseEventHandler | undefined; + onDrag?: import("react").DragEventHandler | undefined; + onDragCapture?: import("react").DragEventHandler | undefined; + onDragEnd?: import("react").DragEventHandler | undefined; + onDragEndCapture?: import("react").DragEventHandler | undefined; + onDragEnter?: import("react").DragEventHandler | undefined; + onDragEnterCapture?: import("react").DragEventHandler | undefined; + onDragExit?: import("react").DragEventHandler | undefined; + onDragExitCapture?: import("react").DragEventHandler | undefined; + onDragLeave?: import("react").DragEventHandler | undefined; + onDragLeaveCapture?: import("react").DragEventHandler | undefined; + onDragOver?: import("react").DragEventHandler | undefined; + onDragOverCapture?: import("react").DragEventHandler | undefined; + onDragStart?: import("react").DragEventHandler | undefined; + onDragStartCapture?: import("react").DragEventHandler | undefined; + onDrop?: import("react").DragEventHandler | undefined; + onDropCapture?: import("react").DragEventHandler | undefined; + onMouseDown?: import("react").MouseEventHandler | undefined; + onMouseDownCapture?: import("react").MouseEventHandler | undefined; + onMouseEnter?: import("react").MouseEventHandler | undefined; + onMouseLeave?: import("react").MouseEventHandler | undefined; + onMouseMove?: import("react").MouseEventHandler | undefined; + onMouseMoveCapture?: import("react").MouseEventHandler | undefined; + onMouseOut?: import("react").MouseEventHandler | undefined; + onMouseOutCapture?: import("react").MouseEventHandler | undefined; + onMouseOver?: import("react").MouseEventHandler | undefined; + onMouseOverCapture?: import("react").MouseEventHandler | undefined; + onMouseUp?: import("react").MouseEventHandler | undefined; + onMouseUpCapture?: import("react").MouseEventHandler | undefined; + onSelect?: import("react").ReactEventHandler | undefined; + onSelectCapture?: import("react").ReactEventHandler | undefined; + onTouchCancel?: import("react").TouchEventHandler | undefined; + onTouchCancelCapture?: import("react").TouchEventHandler | undefined; + onTouchEnd?: import("react").TouchEventHandler | undefined; + onTouchEndCapture?: import("react").TouchEventHandler | undefined; + onTouchMove?: import("react").TouchEventHandler | undefined; + onTouchMoveCapture?: import("react").TouchEventHandler | undefined; + onTouchStart?: import("react").TouchEventHandler | undefined; + onTouchStartCapture?: import("react").TouchEventHandler | undefined; + onPointerDown?: import("react").PointerEventHandler | undefined; + onPointerDownCapture?: import("react").PointerEventHandler | undefined; + onPointerMove?: import("react").PointerEventHandler | undefined; + onPointerMoveCapture?: import("react").PointerEventHandler | undefined; + onPointerUp?: import("react").PointerEventHandler | undefined; + onPointerUpCapture?: import("react").PointerEventHandler | undefined; + onPointerCancel?: import("react").PointerEventHandler | undefined; + onPointerCancelCapture?: import("react").PointerEventHandler | undefined; + onPointerEnter?: import("react").PointerEventHandler | undefined; + onPointerLeave?: import("react").PointerEventHandler | undefined; + onPointerOver?: import("react").PointerEventHandler | undefined; + onPointerOverCapture?: import("react").PointerEventHandler | undefined; + onPointerOut?: import("react").PointerEventHandler | undefined; + onPointerOutCapture?: import("react").PointerEventHandler | undefined; + onGotPointerCapture?: import("react").PointerEventHandler | undefined; + onGotPointerCaptureCapture?: import("react").PointerEventHandler | undefined; + onLostPointerCapture?: import("react").PointerEventHandler | undefined; + onLostPointerCaptureCapture?: import("react").PointerEventHandler | undefined; + onScroll?: import("react").UIEventHandler | undefined; + onScrollCapture?: import("react").UIEventHandler | undefined; + onScrollEnd?: import("react").UIEventHandler | undefined; + onScrollEndCapture?: import("react").UIEventHandler | undefined; + onWheel?: import("react").WheelEventHandler | undefined; + onWheelCapture?: import("react").WheelEventHandler | undefined; + onAnimationStart?: import("react").AnimationEventHandler | undefined; + onAnimationStartCapture?: import("react").AnimationEventHandler | undefined; + onAnimationEnd?: import("react").AnimationEventHandler | undefined; + onAnimationEndCapture?: import("react").AnimationEventHandler | undefined; + onAnimationIteration?: import("react").AnimationEventHandler | undefined; + onAnimationIterationCapture?: import("react").AnimationEventHandler | undefined; + onToggle?: import("react").ToggleEventHandler | undefined; + onBeforeToggle?: import("react").ToggleEventHandler | undefined; + onTransitionCancel?: import("react").TransitionEventHandler | undefined; + onTransitionCancelCapture?: import("react").TransitionEventHandler | undefined; + onTransitionEnd?: import("react").TransitionEventHandler | undefined; + onTransitionEndCapture?: import("react").TransitionEventHandler | undefined; + onTransitionRun?: import("react").TransitionEventHandler | undefined; + onTransitionRunCapture?: import("react").TransitionEventHandler | undefined; + onTransitionStart?: import("react").TransitionEventHandler | undefined; + onTransitionStartCapture?: import("react").TransitionEventHandler | undefined; + }, "ref"> & import("react").RefAttributes>; + redirect: (args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: import("use-intl").Locale; + forcePrefix?: boolean; + }, type?: import("next/dist/client/components/redirect-error.js").RedirectType | undefined) => never; + permanentRedirect: (args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: import("use-intl").Locale; + forcePrefix?: boolean; + }, type?: import("next/dist/client/components/redirect-error.js").RedirectType | undefined) => never; + getPathname: (args: { + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: import("../shared/utils.js").QueryParams; + } : keyof AppPathnames extends infer T_1 ? T_1 extends keyof AppPathnames ? T_1 extends `${string}[[...${string}` ? T_1 | ({ + pathname: T_1; + params?: import("../shared/StrictParams.js").default | undefined; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : T_1 extends `${string}[${string}` ? { + pathname: T_1; + params: import("../shared/StrictParams.js").default; + } & { + query?: import("../shared/utils.js").QueryParams; + } : T_1 | ({ + pathname: T_1; + } & { + query?: import("../shared/utils.js").QueryParams; + }) : never : never; + locale: import("use-intl").Locale; + forcePrefix?: boolean; + }) => string; +}; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/getServerLocale.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/getServerLocale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1445f0cefbe5ca179d1852ae6f2f2b07ec05d1ac --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/getServerLocale.d.ts @@ -0,0 +1,5 @@ +/** + * This is only moved to a separate module for easier mocking in + * `../createNavigatoin.test.tsx` in order to avoid suspending. + */ +export default function getServerLocale(): Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf3e56fadaf9fded07868d88ec866a40401b0cf7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/react-server/index.d.ts @@ -0,0 +1,2 @@ +export { default as createNavigation } from './createNavigation.js'; +export type { Pathnames } from '../../routing/types.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/shared/BaseLink.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/BaseLink.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..72d5a64c44adc661fdc257e7e0baade36af28f07 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/BaseLink.d.ts @@ -0,0 +1,11 @@ +import { type LinkProps } from 'next/link.js'; +import { type ComponentProps } from 'react'; +import { type Locale } from 'use-intl'; +import type { InitializedLocaleCookieConfig } from '../../routing/config.js'; +type NextLinkProps = Omit, keyof LinkProps> & Omit; +type Props = NextLinkProps & { + locale?: Locale; + localeCookie: InitializedLocaleCookieConfig; +}; +declare const _default: import("react").ForwardRefExoticComponent & import("react").RefAttributes>; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/shared/StrictParams.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/StrictParams.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..31225763174092b9c58fdfe2615867d812166148 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/StrictParams.d.ts @@ -0,0 +1,8 @@ +type ParamValue = string | number | boolean; +type ReadFrom = Path extends `${string}[${infer Rest}` ? ReadUntil : []; +type ReadUntil = Path extends `${infer Match}]${infer Rest}` ? [Match, ...ReadFrom] : []; +type RemovePrefixes = Key extends `[...${infer Name}` ? Name : Key extends `...${infer Name}` ? Name : Key; +type StrictParams = Pathname extends `${string}[${string}` ? { + [Key in ReadFrom[number] as RemovePrefixes]: Key extends `[...${string}` ? Array | undefined : Key extends `...${string}` ? Array : ParamValue; +} : never; +export default StrictParams; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/shared/createSharedNavigationFns.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/createSharedNavigationFns.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..241c5188e949b8db8cfa2e1a93753908bf715834 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/createSharedNavigationFns.d.ts @@ -0,0 +1,370 @@ +import type { Locale } from 'use-intl'; +import { type RoutingConfigLocalizedNavigation, type RoutingConfigSharedNavigation } from '../../routing/config.js'; +import type { DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../../routing/types.js'; +import { type HrefOrHrefWithParams, type QueryParams } from './utils.js'; +type PromiseOrValue = Type | Promise; +/** + * Shared implementations for `react-server` and `react-client` + */ +export default function createSharedNavigationFns = never, const AppLocalePrefixMode extends LocalePrefixMode = 'always', const AppDomains extends DomainsConfig = never>(getLocale: () => PromiseOrValue, routing?: [AppPathnames] extends [never] ? RoutingConfigSharedNavigation | undefined : RoutingConfigLocalizedNavigation): { + config: Omit<{}, "localePrefix" | "localeCookie" | "alternateLinks" | "localeDetection"> & { + localePrefix: { + mode: "never"; + } | { + mode: "always"; + prefixes?: Partial> | undefined; + } | { + mode: "as-needed"; + prefixes?: Partial> | undefined; + }; + localeCookie: import("../../routing/config.js").InitializedLocaleCookieConfig; + localeDetection: NonNullable; + alternateLinks: NonNullable; + }; + Link: import("react").ForwardRefExoticComponent | undefined; + prefix?: string | undefined | undefined; + key?: import("react").Key | null | undefined; + as?: (string | import("url").UrlObject) | undefined; + scroll?: boolean | undefined; + shallow?: boolean | undefined; + passHref?: boolean | undefined; + prefetch?: boolean | "auto" | null | undefined; + legacyBehavior?: boolean | undefined; + onNavigate?: ((event: { + preventDefault: () => void; + }) => void) | undefined; + transitionTypes?: string[] | undefined; + download?: any; + hrefLang?: string | undefined | undefined; + media?: string | undefined | undefined; + ping?: string | undefined | undefined; + type?: string | undefined | undefined; + referrerPolicy?: import("react").HTMLAttributeReferrerPolicy | undefined; + defaultChecked?: boolean | undefined | undefined; + defaultValue?: string | number | readonly string[] | undefined; + suppressContentEditableWarning?: boolean | undefined | undefined; + suppressHydrationWarning?: boolean | undefined | undefined; + accessKey?: string | undefined | undefined; + autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | undefined | (string & {}) | undefined; + autoFocus?: boolean | undefined | undefined; + className?: string | undefined | undefined; + contentEditable?: (boolean | "true" | "false") | "inherit" | "plaintext-only" | undefined; + contextMenu?: string | undefined | undefined; + dir?: string | undefined | undefined; + draggable?: (boolean | "true" | "false") | undefined; + enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined | undefined; + hidden?: boolean | undefined | undefined; + lang?: string | undefined | undefined; + nonce?: string | undefined | undefined; + spellCheck?: (boolean | "true" | "false") | undefined; + tabIndex?: number | undefined | undefined; + translate?: "yes" | "no" | undefined | undefined; + radioGroup?: string | undefined | undefined; + role?: import("react").AriaRole | undefined; + about?: string | undefined | undefined; + content?: string | undefined | undefined; + datatype?: string | undefined | undefined; + inlist?: any; + property?: string | undefined | undefined; + rel?: string | undefined | undefined; + resource?: string | undefined | undefined; + rev?: string | undefined | undefined; + typeof?: string | undefined | undefined; + vocab?: string | undefined | undefined; + autoCorrect?: string | undefined | undefined; + autoSave?: string | undefined | undefined; + color?: string | undefined | undefined; + itemProp?: string | undefined | undefined; + itemScope?: boolean | undefined | undefined; + itemType?: string | undefined | undefined; + itemID?: string | undefined | undefined; + itemRef?: string | undefined | undefined; + results?: number | undefined | undefined; + security?: string | undefined | undefined; + unselectable?: "on" | "off" | undefined | undefined; + popover?: "" | "auto" | "manual" | "hint" | undefined | undefined; + popoverTargetAction?: "toggle" | "show" | "hide" | undefined | undefined; + popoverTarget?: string | undefined | undefined; + inert?: boolean | undefined | undefined; + inputMode?: "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined | undefined; + is?: string | undefined | undefined; + exportparts?: string | undefined | undefined; + part?: string | undefined | undefined; + "aria-activedescendant"?: string | undefined | undefined; + "aria-atomic"?: (boolean | "true" | "false") | undefined; + "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined | undefined; + "aria-braillelabel"?: string | undefined | undefined; + "aria-brailleroledescription"?: string | undefined | undefined; + "aria-busy"?: (boolean | "true" | "false") | undefined; + "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined | undefined; + "aria-colcount"?: number | undefined | undefined; + "aria-colindex"?: number | undefined | undefined; + "aria-colindextext"?: string | undefined | undefined; + "aria-colspan"?: number | undefined | undefined; + "aria-controls"?: string | undefined | undefined; + "aria-current"?: boolean | "false" | "true" | "page" | "step" | "location" | "date" | "time" | undefined | undefined; + "aria-describedby"?: string | undefined | undefined; + "aria-description"?: string | undefined | undefined; + "aria-details"?: string | undefined | undefined; + "aria-disabled"?: (boolean | "true" | "false") | undefined; + "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined | undefined; + "aria-errormessage"?: string | undefined | undefined; + "aria-expanded"?: (boolean | "true" | "false") | undefined; + "aria-flowto"?: string | undefined | undefined; + "aria-grabbed"?: (boolean | "true" | "false") | undefined; + "aria-haspopup"?: boolean | "false" | "true" | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined | undefined; + "aria-hidden"?: (boolean | "true" | "false") | undefined; + "aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling" | undefined | undefined; + "aria-keyshortcuts"?: string | undefined | undefined; + "aria-label"?: string | undefined | undefined; + "aria-labelledby"?: string | undefined | undefined; + "aria-level"?: number | undefined | undefined; + "aria-live"?: "off" | "assertive" | "polite" | undefined | undefined; + "aria-modal"?: (boolean | "true" | "false") | undefined; + "aria-multiline"?: (boolean | "true" | "false") | undefined; + "aria-multiselectable"?: (boolean | "true" | "false") | undefined; + "aria-orientation"?: "horizontal" | "vertical" | undefined | undefined; + "aria-owns"?: string | undefined | undefined; + "aria-placeholder"?: string | undefined | undefined; + "aria-posinset"?: number | undefined | undefined; + "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined | undefined; + "aria-readonly"?: (boolean | "true" | "false") | undefined; + "aria-relevant"?: "additions" | "additions removals" | "additions text" | "all" | "removals" | "removals additions" | "removals text" | "text" | "text additions" | "text removals" | undefined | undefined; + "aria-required"?: (boolean | "true" | "false") | undefined; + "aria-roledescription"?: string | undefined | undefined; + "aria-rowcount"?: number | undefined | undefined; + "aria-rowindex"?: number | undefined | undefined; + "aria-rowindextext"?: string | undefined | undefined; + "aria-rowspan"?: number | undefined | undefined; + "aria-selected"?: (boolean | "true" | "false") | undefined; + "aria-setsize"?: number | undefined | undefined; + "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined | undefined; + "aria-valuemax"?: number | undefined | undefined; + "aria-valuemin"?: number | undefined | undefined; + "aria-valuenow"?: number | undefined | undefined; + "aria-valuetext"?: string | undefined | undefined; + href: [AppPathnames] extends [never] ? string | import("url").UrlObject : keyof AppPathnames extends infer T ? T extends keyof AppPathnames ? T extends `${string}[[...${string}` ? T | ({ + pathname: T; + params?: import("./StrictParams.js").default | undefined; + } & Omit) : T extends `${string}[${string}` ? { + pathname: T; + params: import("./StrictParams.js").default; + } & Omit : T | ({ + pathname: T; + } & Omit) : never : never; + children?: import("react").ReactNode; + dangerouslySetInnerHTML?: { + __html: string | TrustedHTML; + } | undefined | undefined; + onCopy?: import("react").ClipboardEventHandler | undefined; + onCopyCapture?: import("react").ClipboardEventHandler | undefined; + onCut?: import("react").ClipboardEventHandler | undefined; + onCutCapture?: import("react").ClipboardEventHandler | undefined; + onPaste?: import("react").ClipboardEventHandler | undefined; + onPasteCapture?: import("react").ClipboardEventHandler | undefined; + onCompositionEnd?: import("react").CompositionEventHandler | undefined; + onCompositionEndCapture?: import("react").CompositionEventHandler | undefined; + onCompositionStart?: import("react").CompositionEventHandler | undefined; + onCompositionStartCapture?: import("react").CompositionEventHandler | undefined; + onCompositionUpdate?: import("react").CompositionEventHandler | undefined; + onCompositionUpdateCapture?: import("react").CompositionEventHandler | undefined; + onFocus?: import("react").FocusEventHandler | undefined; + onFocusCapture?: import("react").FocusEventHandler | undefined; + onBlur?: import("react").FocusEventHandler | undefined; + onBlurCapture?: import("react").FocusEventHandler | undefined; + onChange?: import("react").ChangeEventHandler | undefined; + onChangeCapture?: import("react").ChangeEventHandler | undefined; + onBeforeInput?: import("react").InputEventHandler | undefined; + onBeforeInputCapture?: import("react").InputEventHandler | undefined; + onInput?: import("react").InputEventHandler | undefined; + onInputCapture?: import("react").InputEventHandler | undefined; + onReset?: import("react").ReactEventHandler | undefined; + onResetCapture?: import("react").ReactEventHandler | undefined; + onSubmit?: import("react").SubmitEventHandler | undefined; + onSubmitCapture?: import("react").SubmitEventHandler | undefined; + onInvalid?: import("react").ReactEventHandler | undefined; + onInvalidCapture?: import("react").ReactEventHandler | undefined; + onLoad?: import("react").ReactEventHandler | undefined; + onLoadCapture?: import("react").ReactEventHandler | undefined; + onError?: import("react").ReactEventHandler | undefined; + onErrorCapture?: import("react").ReactEventHandler | undefined; + onKeyDown?: import("react").KeyboardEventHandler | undefined; + onKeyDownCapture?: import("react").KeyboardEventHandler | undefined; + onKeyPress?: import("react").KeyboardEventHandler | undefined; + onKeyPressCapture?: import("react").KeyboardEventHandler | undefined; + onKeyUp?: import("react").KeyboardEventHandler | undefined; + onKeyUpCapture?: import("react").KeyboardEventHandler | undefined; + onAbort?: import("react").ReactEventHandler | undefined; + onAbortCapture?: import("react").ReactEventHandler | undefined; + onCanPlay?: import("react").ReactEventHandler | undefined; + onCanPlayCapture?: import("react").ReactEventHandler | undefined; + onCanPlayThrough?: import("react").ReactEventHandler | undefined; + onCanPlayThroughCapture?: import("react").ReactEventHandler | undefined; + onDurationChange?: import("react").ReactEventHandler | undefined; + onDurationChangeCapture?: import("react").ReactEventHandler | undefined; + onEmptied?: import("react").ReactEventHandler | undefined; + onEmptiedCapture?: import("react").ReactEventHandler | undefined; + onEncrypted?: import("react").ReactEventHandler | undefined; + onEncryptedCapture?: import("react").ReactEventHandler | undefined; + onEnded?: import("react").ReactEventHandler | undefined; + onEndedCapture?: import("react").ReactEventHandler | undefined; + onLoadedData?: import("react").ReactEventHandler | undefined; + onLoadedDataCapture?: import("react").ReactEventHandler | undefined; + onLoadedMetadata?: import("react").ReactEventHandler | undefined; + onLoadedMetadataCapture?: import("react").ReactEventHandler | undefined; + onLoadStart?: import("react").ReactEventHandler | undefined; + onLoadStartCapture?: import("react").ReactEventHandler | undefined; + onPause?: import("react").ReactEventHandler | undefined; + onPauseCapture?: import("react").ReactEventHandler | undefined; + onPlay?: import("react").ReactEventHandler | undefined; + onPlayCapture?: import("react").ReactEventHandler | undefined; + onPlaying?: import("react").ReactEventHandler | undefined; + onPlayingCapture?: import("react").ReactEventHandler | undefined; + onProgress?: import("react").ReactEventHandler | undefined; + onProgressCapture?: import("react").ReactEventHandler | undefined; + onRateChange?: import("react").ReactEventHandler | undefined; + onRateChangeCapture?: import("react").ReactEventHandler | undefined; + onSeeked?: import("react").ReactEventHandler | undefined; + onSeekedCapture?: import("react").ReactEventHandler | undefined; + onSeeking?: import("react").ReactEventHandler | undefined; + onSeekingCapture?: import("react").ReactEventHandler | undefined; + onStalled?: import("react").ReactEventHandler | undefined; + onStalledCapture?: import("react").ReactEventHandler | undefined; + onSuspend?: import("react").ReactEventHandler | undefined; + onSuspendCapture?: import("react").ReactEventHandler | undefined; + onTimeUpdate?: import("react").ReactEventHandler | undefined; + onTimeUpdateCapture?: import("react").ReactEventHandler | undefined; + onVolumeChange?: import("react").ReactEventHandler | undefined; + onVolumeChangeCapture?: import("react").ReactEventHandler | undefined; + onWaiting?: import("react").ReactEventHandler | undefined; + onWaitingCapture?: import("react").ReactEventHandler | undefined; + onAuxClick?: import("react").MouseEventHandler | undefined; + onAuxClickCapture?: import("react").MouseEventHandler | undefined; + onClick?: import("react").MouseEventHandler | undefined; + onClickCapture?: import("react").MouseEventHandler | undefined; + onContextMenu?: import("react").MouseEventHandler | undefined; + onContextMenuCapture?: import("react").MouseEventHandler | undefined; + onDoubleClick?: import("react").MouseEventHandler | undefined; + onDoubleClickCapture?: import("react").MouseEventHandler | undefined; + onDrag?: import("react").DragEventHandler | undefined; + onDragCapture?: import("react").DragEventHandler | undefined; + onDragEnd?: import("react").DragEventHandler | undefined; + onDragEndCapture?: import("react").DragEventHandler | undefined; + onDragEnter?: import("react").DragEventHandler | undefined; + onDragEnterCapture?: import("react").DragEventHandler | undefined; + onDragExit?: import("react").DragEventHandler | undefined; + onDragExitCapture?: import("react").DragEventHandler | undefined; + onDragLeave?: import("react").DragEventHandler | undefined; + onDragLeaveCapture?: import("react").DragEventHandler | undefined; + onDragOver?: import("react").DragEventHandler | undefined; + onDragOverCapture?: import("react").DragEventHandler | undefined; + onDragStart?: import("react").DragEventHandler | undefined; + onDragStartCapture?: import("react").DragEventHandler | undefined; + onDrop?: import("react").DragEventHandler | undefined; + onDropCapture?: import("react").DragEventHandler | undefined; + onMouseDown?: import("react").MouseEventHandler | undefined; + onMouseDownCapture?: import("react").MouseEventHandler | undefined; + onMouseEnter?: import("react").MouseEventHandler | undefined; + onMouseLeave?: import("react").MouseEventHandler | undefined; + onMouseMove?: import("react").MouseEventHandler | undefined; + onMouseMoveCapture?: import("react").MouseEventHandler | undefined; + onMouseOut?: import("react").MouseEventHandler | undefined; + onMouseOutCapture?: import("react").MouseEventHandler | undefined; + onMouseOver?: import("react").MouseEventHandler | undefined; + onMouseOverCapture?: import("react").MouseEventHandler | undefined; + onMouseUp?: import("react").MouseEventHandler | undefined; + onMouseUpCapture?: import("react").MouseEventHandler | undefined; + onSelect?: import("react").ReactEventHandler | undefined; + onSelectCapture?: import("react").ReactEventHandler | undefined; + onTouchCancel?: import("react").TouchEventHandler | undefined; + onTouchCancelCapture?: import("react").TouchEventHandler | undefined; + onTouchEnd?: import("react").TouchEventHandler | undefined; + onTouchEndCapture?: import("react").TouchEventHandler | undefined; + onTouchMove?: import("react").TouchEventHandler | undefined; + onTouchMoveCapture?: import("react").TouchEventHandler | undefined; + onTouchStart?: import("react").TouchEventHandler | undefined; + onTouchStartCapture?: import("react").TouchEventHandler | undefined; + onPointerDown?: import("react").PointerEventHandler | undefined; + onPointerDownCapture?: import("react").PointerEventHandler | undefined; + onPointerMove?: import("react").PointerEventHandler | undefined; + onPointerMoveCapture?: import("react").PointerEventHandler | undefined; + onPointerUp?: import("react").PointerEventHandler | undefined; + onPointerUpCapture?: import("react").PointerEventHandler | undefined; + onPointerCancel?: import("react").PointerEventHandler | undefined; + onPointerCancelCapture?: import("react").PointerEventHandler | undefined; + onPointerEnter?: import("react").PointerEventHandler | undefined; + onPointerLeave?: import("react").PointerEventHandler | undefined; + onPointerOver?: import("react").PointerEventHandler | undefined; + onPointerOverCapture?: import("react").PointerEventHandler | undefined; + onPointerOut?: import("react").PointerEventHandler | undefined; + onPointerOutCapture?: import("react").PointerEventHandler | undefined; + onGotPointerCapture?: import("react").PointerEventHandler | undefined; + onGotPointerCaptureCapture?: import("react").PointerEventHandler | undefined; + onLostPointerCapture?: import("react").PointerEventHandler | undefined; + onLostPointerCaptureCapture?: import("react").PointerEventHandler | undefined; + onScroll?: import("react").UIEventHandler | undefined; + onScrollCapture?: import("react").UIEventHandler | undefined; + onScrollEnd?: import("react").UIEventHandler | undefined; + onScrollEndCapture?: import("react").UIEventHandler | undefined; + onWheel?: import("react").WheelEventHandler | undefined; + onWheelCapture?: import("react").WheelEventHandler | undefined; + onAnimationStart?: import("react").AnimationEventHandler | undefined; + onAnimationStartCapture?: import("react").AnimationEventHandler | undefined; + onAnimationEnd?: import("react").AnimationEventHandler | undefined; + onAnimationEndCapture?: import("react").AnimationEventHandler | undefined; + onAnimationIteration?: import("react").AnimationEventHandler | undefined; + onAnimationIterationCapture?: import("react").AnimationEventHandler | undefined; + onToggle?: import("react").ToggleEventHandler | undefined; + onBeforeToggle?: import("react").ToggleEventHandler | undefined; + onTransitionCancel?: import("react").TransitionEventHandler | undefined; + onTransitionCancelCapture?: import("react").TransitionEventHandler | undefined; + onTransitionEnd?: import("react").TransitionEventHandler | undefined; + onTransitionEndCapture?: import("react").TransitionEventHandler | undefined; + onTransitionRun?: import("react").TransitionEventHandler | undefined; + onTransitionRunCapture?: import("react").TransitionEventHandler | undefined; + onTransitionStart?: import("react").TransitionEventHandler | undefined; + onTransitionStartCapture?: import("react").TransitionEventHandler | undefined; + }, "ref"> & import("react").RefAttributes>; + redirect: (args: Parameters<(args: { + /** @see https://next-intl.dev/docs/routing/navigation#getpathname */ + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: QueryParams; + } : HrefOrHrefWithParams; + /** The locale to compute the pathname for. */ + locale: Locale; + /** Will prepend the pathname with the locale prefix, regardless of your `localePrefix` setting. This can be helpful to update a locale cookie when changing locales. */ + forcePrefix?: boolean; + }) => string>[0], type?: import("next/dist/client/components/redirect-error.js").RedirectType | undefined) => never; + permanentRedirect: (args: Parameters<(args: { + /** @see https://next-intl.dev/docs/routing/navigation#getpathname */ + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: QueryParams; + } : HrefOrHrefWithParams; + /** The locale to compute the pathname for. */ + locale: Locale; + /** Will prepend the pathname with the locale prefix, regardless of your `localePrefix` setting. This can be helpful to update a locale cookie when changing locales. */ + forcePrefix?: boolean; + }) => string>[0], type?: import("next/dist/client/components/redirect-error.js").RedirectType | undefined) => never; + getPathname: (args: { + /** @see https://next-intl.dev/docs/routing/navigation#getpathname */ + href: [AppPathnames] extends [never] ? string | { + pathname: string; + query?: QueryParams; + } : HrefOrHrefWithParams; + /** The locale to compute the pathname for. */ + locale: Locale; + /** Will prepend the pathname with the locale prefix, regardless of your `localePrefix` setting. This can be helpful to update a locale cookie when changing locales. */ + forcePrefix?: boolean; + }) => string; +}; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/shared/syncLocaleCookie.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/syncLocaleCookie.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea9531e5534bf97b6a5db80db8936daed54b0d7a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/syncLocaleCookie.d.ts @@ -0,0 +1,8 @@ +import type { Locale } from 'use-intl'; +import type { InitializedLocaleCookieConfig } from '../../routing/config.js'; +/** + * We have to keep the cookie value in sync as Next.js might + * skip a request to the server due to its router cache. + * See https://github.com/amannn/next-intl/issues/786. + */ +export default function syncLocaleCookie(localeCookie: InitializedLocaleCookieConfig, locale: Locale, nextLocale?: Locale): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/navigation/shared/utils.d.ts b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b77111eae7f8b917740bd03c8df6627012babae --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/navigation/shared/utils.d.ts @@ -0,0 +1,53 @@ +import type { ParsedUrlQueryInput } from 'node:querystring'; +import type { UrlObject } from 'url'; +import type { Locale } from 'use-intl'; +import type { ResolvedRoutingConfig } from '../../routing/config.js'; +import type { DomainsConfig, LocalePrefixMode, Locales, Pathnames } from '../../routing/types.js'; +import type StrictParams from './StrictParams.js'; +type SearchParamValue = ParsedUrlQueryInput[keyof ParsedUrlQueryInput]; +type HrefOrHrefWithParamsImpl = Pathname extends `${string}[[...${string}` ? Pathname | ({ + pathname: Pathname; + params?: StrictParams; +} & Other) : Pathname extends `${string}[${string}` ? // Required catch-all & regular params +{ + pathname: Pathname; + params: StrictParams; +} & Other : // No params +Pathname | ({ + pathname: Pathname; +} & Other); +export type HrefOrUrlObjectWithParams = HrefOrHrefWithParamsImpl>; +export type QueryParams = Record; +export type HrefOrHrefWithParams = HrefOrHrefWithParamsImpl; +export declare function normalizeNameOrNameWithParams(href: HrefOrHrefWithParams | { + locale: Locale; + href: HrefOrHrefWithParams; +}): { + pathname: Pathname; + params?: StrictParams; +}; +export declare function serializeSearchParams(searchParams: Record): string; +type StrictUrlObject = Omit & { + pathname: Pathname; +}; +export declare function compileLocalizedPathname(opts: { + locale: AppLocales[number]; + pathname: Pathname; + params?: StrictParams; + pathnames: Pathnames; + query?: Record; +}): string; +export declare function compileLocalizedPathname(opts: { + locale: AppLocales[number]; + pathname: StrictUrlObject; + params?: StrictParams; + pathnames: Pathnames; + query?: Record; +}): UrlObject; +export declare function getRoute(locale: AppLocales[number], pathname: string, pathnames: Pathnames): keyof Pathnames; +export declare function getBasePath(): string; +export declare function applyPathnamePrefix | undefined, AppDomains extends DomainsConfig | undefined>(pathname: string, locale: Locales[number], routing: Pick, 'localePrefix' | 'domains'> & Partial, 'defaultLocale'>>, force?: boolean): string; +export declare function validateReceivedConfig | undefined, AppDomains extends DomainsConfig | undefined>(config: Partial, 'defaultLocale' | 'localePrefix'>>): void; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..184ce0af4de7f61b12c47e43a02250414ff5153e --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin.d.ts @@ -0,0 +1 @@ +export { default } from './plugin/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/catalog/catalogLoader.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/catalog/catalogLoader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0f6f7ecf0e3367c309e6fcc35476a7ef6008e5f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/catalog/catalogLoader.d.ts @@ -0,0 +1,10 @@ +import type { CatalogLoaderConfig } from '../../extractor/types.js'; +import type { TurbopackLoaderContext } from '../types.js'; +/** + * Parses and optimizes catalog files. + * + * Note that if we use a dynamic import like `import(`${locale}.json`)`, then + * the loader will optimistically run for all candidates in this folder (both + * during dev as well as at build time). + */ +export default function catalogLoader(this: TurbopackLoaderContext, source: string): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/config.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7c1eda73f0de991ac4a495ccd8a7cda9c3dfc07 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/config.d.ts @@ -0,0 +1,3 @@ +export declare const isDevelopment: boolean; +export declare const isNextBuild: boolean; +export declare const isDevelopmentOrNextBuild: boolean; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/createNextIntlPlugin.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/createNextIntlPlugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..174ad0dbe212e68a657a4e56e8d682437ef80802 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/createNextIntlPlugin.d.ts @@ -0,0 +1,3 @@ +import type { NextConfig } from 'next'; +import type { PluginConfig } from './types.js'; +export default function createNextIntlPlugin(i18nPathOrConfig?: string | PluginConfig): (nextConfig?: NextConfig) => NextConfig; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/declaration/createMessagesDeclaration.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/declaration/createMessagesDeclaration.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf64d325b18a0e9c68af8d8cfc2ef8f01ff50186 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/declaration/createMessagesDeclaration.d.ts @@ -0,0 +1 @@ +export default function createMessagesDeclaration(messagesPaths: Array): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/declaration/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/declaration/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10db34a04f61cc10bcfede2fb900627b5c963118 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/declaration/index.d.ts @@ -0,0 +1 @@ +export { default } from './createMessagesDeclaration.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/extractor/extractionLoader.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/extractor/extractionLoader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15dccd2154939e4d20be0798a8eee582c10a90cf --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/extractor/extractionLoader.d.ts @@ -0,0 +1,3 @@ +import type { ExtractorConfig } from '../../extractor/types.js'; +import type { TurbopackLoaderContext } from '../types.js'; +export default function extractionLoader(this: TurbopackLoaderContext, source: string): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/extractor/initExtractionCompiler.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/extractor/initExtractionCompiler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad5fabfd605c7ad84a1d2894fcf23cbd510ff64b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/extractor/initExtractionCompiler.d.ts @@ -0,0 +1,2 @@ +import type { ExtractorConfig } from '../../extractor/types.js'; +export default function initExtractionCompiler(extractorConfig?: ExtractorConfig): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/getNextConfig.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/getNextConfig.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2aceb3c91314aadbf23c19bc46fa2efb16369f2 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/getNextConfig.d.ts @@ -0,0 +1,4 @@ +import type { NextConfig } from 'next'; +import type { ExtractorConfig } from '../extractor/types.js'; +import type { PluginConfig } from './types.js'; +export default function getNextConfig(pluginConfig: PluginConfig, nextConfig?: NextConfig, extractorConfig?: ExtractorConfig): NextConfig & Partial; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8904839b45ff6c170210f92f96c0e1eb50cb8b76 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/index.d.ts @@ -0,0 +1 @@ +export { default } from './createNextIntlPlugin.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/nextFlags.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/nextFlags.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf77435aeaf32511e65d98442c278c4ce1410e1b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/nextFlags.d.ts @@ -0,0 +1,2 @@ +export declare function hasStableTurboConfig(): boolean; +export declare function isNextJs16OrHigher(): boolean; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/types.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b088d86e7be803c217705e640687457c34ce4d6 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/types.d.ts @@ -0,0 +1,25 @@ +import type { LoaderContext } from 'webpack'; +import type { ExtractorConfigInput } from '../extractor/types.js'; +export type PluginConfig = { + requestConfig?: string; + experimental?: { + /** A path to the messages file that you'd like to create a declaration for. In case you want to consider multiple files, you can pass an array of paths. */ + createMessagesDeclaration?: string | Array; + /** + * Relative path(s) to your source code files. + */ + srcPath?: string | Array; + /** Configuration about your catalogs of messages */ + messages?: ExtractorConfigInput['messages'] & { + /** + * When enabled, ICU messages are precompiled at build time, resulting in smaller bundles and faster message formatting. + */ + precompile?: boolean; + }; + /** + * Enables the usage of [`useExtracted`](/docs/usage/extraction). + */ + extract?: ExtractorConfigInput['extract']; + }; +}; +export type TurbopackLoaderContext = Pick, 'rootContext' | 'sourceMap' | 'getOptions' | 'getResolve' | 'emitWarning' | 'emitError' | 'getLogger' | 'context' | 'loaderIndex' | 'loaders' | 'resourcePath' | 'resourceQuery' | 'resourceFragment' | 'async' | 'callback' | 'cacheable' | 'addDependency' | 'dependency' | 'addContextDependency' | 'addMissingDependency' | 'getDependencies' | 'getContextDependencies' | 'getMissingDependencies' | 'clearDependencies' | 'resource' | 'request' | 'remainingRequest' | 'currentRequest' | 'previousRequest' | 'query' | 'data'>; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/utils.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a6271b3707d888d50992731df64a32737916340 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/utils.d.ts @@ -0,0 +1,8 @@ +export declare function throwError(message: string): never; +export declare function warn(message: string): void; +/** + * Returns a function that runs the provided callback only once per process. + * Next.js can call the config multiple times - this ensures we only run once. + * Uses an environment variable to track execution across config loads. + */ +export declare function once(namespace: string): (fn: () => void) => void; diff --git a/e-commerce/node_modules/next-intl/dist/types/plugin/watchFile.d.ts b/e-commerce/node_modules/next-intl/dist/types/plugin/watchFile.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a87fa39e21cfd447e1c4f6e94bb090c237f795b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/plugin/watchFile.d.ts @@ -0,0 +1,6 @@ +import fs from 'fs'; +/** + * Wrapper around `fs.watch` that provides a workaround + * for https://github.com/nodejs/node/issues/5039. + */ +export default function watchFile(filepath: string, callback: () => void): fs.FSWatcher; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-client/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-client/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b11e54870619359d94c34076d9dfecc25c60adb5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-client/index.d.ts @@ -0,0 +1,16 @@ +/** + * This is the main entry file when non-'react-server' + * environments import from 'next-intl'. + * + * Maintainer notes: + * - Make sure this mirrors the API from 'react-server'. + * - Make sure everything exported from this module is + * supported in all Next.js versions that are supported. + */ +import { useFormatter as base_useFormatter, useTranslations as base_useTranslations } from 'use-intl'; +export * from 'use-intl/core'; +export { IntlProvider, useLocale, useNow, useTimeZone, useMessages } from 'use-intl/react'; +export { _useExtracted as useExtracted } from 'use-intl/react'; +export declare const useTranslations: typeof base_useTranslations; +export declare const useFormatter: typeof base_useFormatter; +export { default as NextIntlClientProvider } from '../shared/NextIntlClientProvider.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/NextIntlClientProviderServer.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/NextIntlClientProviderServer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9914a0d3ca1a5fb538d5f0ed506e01593fdfb63 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/NextIntlClientProviderServer.d.ts @@ -0,0 +1,5 @@ +import type { ComponentProps } from 'react'; +import BaseNextIntlClientProvider from '../shared/NextIntlClientProvider.js'; +type Props = ComponentProps; +export default function NextIntlClientProviderServer({ formats, locale, messages, now, timeZone, ...rest }: Props): Promise; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..32a724f2e0d6c193fe28749293ddb3a3cf998f6b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/index.d.ts @@ -0,0 +1,16 @@ +/** + * This is the main entry file when 'react-server' environments + * (i.e. RSC) import from 'next-intl'. Currently we export everything + * from `use-intl` core, but React-APIs are stubbed out. + * + * Make sure this mirrors the API from '../react-client'. + */ +export { default as useLocale } from './useLocale.js'; +export { default as useTranslations } from './useTranslations.js'; +export { default as useFormatter } from './useFormatter.js'; +export { default as useNow } from './useNow.js'; +export { default as useTimeZone } from './useTimeZone.js'; +export { default as useMessages } from './useMessages.js'; +export { default as NextIntlClientProvider } from './NextIntlClientProviderServer.js'; +export { default as useExtracted } from './useExtracted.js'; +export * from 'use-intl/core'; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/testUtils.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/testUtils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..402f8275e5e7408884f7b2270f7381a5a7f68a01 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/testUtils.d.ts @@ -0,0 +1,2 @@ +import { type ReactNode } from 'react'; +export declare function renderToStream(children: ReactNode): Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useConfig.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useConfig.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fd44c9d393208df252d161008aaca71c23e285a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useConfig.d.ts @@ -0,0 +1,2 @@ +import getConfig from '../server/react-server/getConfig.js'; +export default function useConfig(hookName: string): Awaited>; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useExtracted.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useExtracted.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..238e94953cd5e535cab96d7681d771384b6f79f0 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useExtracted.d.ts @@ -0,0 +1,2 @@ +import getServerExtractor from '../server/react-server/getServerExtractor.js'; +export default function useExtracted(namespace?: string): ReturnType; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useFormatter.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useFormatter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcf9f8d24751edc55b3d928370df995d68e74d2d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useFormatter.d.ts @@ -0,0 +1,2 @@ +import type { useFormatter as useFormatterType } from 'use-intl'; +export default function useFormatter(): ReturnType; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useLocale.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useLocale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..551d88a054a3bab76095b9844271a9d7d995768c --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useLocale.d.ts @@ -0,0 +1,2 @@ +import type { useLocale as useLocaleType } from 'use-intl'; +export default function useLocale(): ReturnType; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useMessages.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useMessages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e969d45e75eabb73f2835982ba22a0c39b60e73 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useMessages.d.ts @@ -0,0 +1,2 @@ +import type { useMessages as useMessagesType } from 'use-intl'; +export default function useMessages(): ReturnType; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useNow.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useNow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..405968243c456f17a1cdfbe33629079ceebc72dc --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useNow.d.ts @@ -0,0 +1,2 @@ +import type { useNow as useNowType } from 'use-intl'; +export default function useNow(options?: Parameters[0]): ReturnType; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useTimeZone.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useTimeZone.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8d6f38fd6a0d42cf04304ae62f9a1aa41ba7ac5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useTimeZone.d.ts @@ -0,0 +1,2 @@ +import type { useTimeZone as useTimeZoneType } from 'use-intl'; +export default function useTimeZone(): ReturnType; diff --git a/e-commerce/node_modules/next-intl/dist/types/react-server/useTranslations.d.ts b/e-commerce/node_modules/next-intl/dist/types/react-server/useTranslations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..55537217c687fd7f11aa914ba00db8c580581e32 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/react-server/useTranslations.d.ts @@ -0,0 +1,2 @@ +import type { useTranslations as useTranslationsType } from 'use-intl'; +export default function useTranslations(...[namespace]: Parameters): ReturnType; diff --git a/e-commerce/node_modules/next-intl/dist/types/routing.d.ts b/e-commerce/node_modules/next-intl/dist/types/routing.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6928797912f1f0a9c3100c9750f0782b77d23222 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/routing.d.ts @@ -0,0 +1 @@ +export * from './routing/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/routing/config.d.ts b/e-commerce/node_modules/next-intl/dist/types/routing/config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ac199428198aaa806cc3813cdcec1ee9b84db8b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/routing/config.d.ts @@ -0,0 +1,73 @@ +import type { NextResponse } from 'next/server.js'; +import type { DomainsConfig, LocalePrefix, LocalePrefixConfigVerbose, LocalePrefixMode, Locales, Pathnames } from './types.js'; +type CookieAttributes = Pick['2']>, 'maxAge' | 'domain' | 'partitioned' | 'path' | 'priority' | 'sameSite' | 'secure' | 'name'>; +export type RoutingConfig | undefined, AppDomains extends DomainsConfig | undefined> = { + /** + * All available locales. + * @see https://next-intl.dev/docs/routing + */ + locales: AppLocales; + /** + * Used when no locale matches. + * @see https://next-intl.dev/docs/routing + */ + defaultLocale: AppLocales[number]; + /** + * Configures whether and which prefix is shown for a given locale. + * @see https://next-intl.dev/docs/routing/configuration#locale-prefix + **/ + localePrefix?: LocalePrefix; + /** + * Can be used to change the locale handling per domain. + * @see https://next-intl.dev/docs/routing/configuration#domains + **/ + domains?: AppDomains; + /** + * Can be used to disable the locale cookie or to customize it. + * @see https://next-intl.dev/docs/routing/middleware#locale-cookie + */ + localeCookie?: boolean | CookieAttributes; + /** + * Sets the `Link` response header to notify search engines about content in other languages (defaults to `true`). See https://developers.google.com/search/docs/specialty/international/localized-versions#http + * @see https://next-intl.dev/docs/routing/middleware#alternate-links + **/ + alternateLinks?: boolean; + /** + * By setting this to `false`, the cookie as well as the `accept-language` header will no longer be used for locale detection. + * @see https://next-intl.dev/docs/routing/middleware#locale-detection + **/ + localeDetection?: boolean; +} & ([AppPathnames] extends [never] ? {} : { + /** + * A map of localized pathnames per locale. + * @see https://next-intl.dev/docs/routing/configuration#pathnames + **/ + pathnames: AppPathnames; +}); +export type RoutingConfigSharedNavigation = never> = Omit, 'defaultLocale' | 'locales' | 'pathnames'> & Partial, 'defaultLocale' | 'locales'>>; +export type RoutingConfigLocalizedNavigation, AppDomains extends DomainsConfig = never> = Omit, 'defaultLocale' | 'pathnames'> & Partial, 'defaultLocale'>> & { + pathnames: AppPathnames; +}; +export type ResolvedRoutingConfig | undefined, AppDomains extends DomainsConfig | undefined> = Omit, 'localePrefix' | 'localeCookie' | 'alternateLinks' | 'localeDetection'> & { + localePrefix: LocalePrefixConfigVerbose; + localeCookie: InitializedLocaleCookieConfig; + alternateLinks: boolean; + localeDetection: boolean; +}; +export declare function receiveRoutingConfig | undefined, AppDomains extends DomainsConfig | undefined, Config extends Partial>>(input: Config): Omit & { + localePrefix: { + mode: "never"; + } | { + mode: "always"; + prefixes?: Partial> | undefined; + } | { + mode: "as-needed"; + prefixes?: Partial> | undefined; + }; + localeCookie: InitializedLocaleCookieConfig; + localeDetection: boolean | NonNullable["localeDetection"]>; + alternateLinks: boolean | NonNullable["alternateLinks"]>; +}; +export type InitializedLocaleCookieConfig = false | LocaleCookieConfig; +export type LocaleCookieConfig = Omit & Required>; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/routing/defineRouting.d.ts b/e-commerce/node_modules/next-intl/dist/types/routing/defineRouting.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..87fa2feb2b2ffc3b3c72afdb21a6d9f7379302b3 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/routing/defineRouting.d.ts @@ -0,0 +1,3 @@ +import type { RoutingConfig } from './config.js'; +import type { DomainsConfig, LocalePrefixMode, Locales, Pathnames } from './types.js'; +export default function defineRouting = never, const AppDomains extends DomainsConfig = never>(config: RoutingConfig): RoutingConfig; diff --git a/e-commerce/node_modules/next-intl/dist/types/routing/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/routing/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..38bc3a8ef363580c763c87dc6b13783f3604a2f7 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/routing/index.d.ts @@ -0,0 +1,3 @@ +export type { Pathnames, LocalePrefix, DomainsConfig, LocalePrefixMode } from './types.js'; +export { default as defineRouting } from './defineRouting.js'; +export type { RoutingConfig } from './config.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/routing/types.d.ts b/e-commerce/node_modules/next-intl/dist/types/routing/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fb6f32cf3f6e2d08bd6ba336d936193315fd687 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/routing/types.d.ts @@ -0,0 +1,25 @@ +export type Locales = ReadonlyArray; +export type LocalePrefixMode = 'always' | 'as-needed' | 'never'; +type Pathname = string; +export type LocalePrefixes = Partial>; +export type LocalePrefixConfigVerbose = AppLocalePrefixMode extends 'always' ? { + mode: 'always'; + prefixes?: LocalePrefixes; +} : AppLocalePrefixMode extends 'as-needed' ? { + mode: 'as-needed'; + prefixes?: LocalePrefixes; +} : { + mode: 'never'; +}; +export type LocalePrefix = AppLocalePrefixMode | LocalePrefixConfigVerbose; +export type Pathnames = Record> | Pathname>; +export type DomainConfig = { + localePrefix?: LocalePrefixMode; + defaultLocale: AppLocales[number]; + /** The domain name (e.g. "example.com", "www.example.com" or "fr.example.com"). Note that the `x-forwarded-host` or alternatively the `host` header will be used to determine the requested domain. */ + domain: string; + /** The locales that are available on this domain. */ + locales: Array; +}; +export type DomainsConfig = Array>; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/server.react-client.d.ts b/e-commerce/node_modules/next-intl/dist/types/server.react-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf320e6f1a6d12fd8813417fcf2b266d8695f687 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server.react-client.d.ts @@ -0,0 +1 @@ +export * from './server/react-client/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/server.react-server.d.ts b/e-commerce/node_modules/next-intl/dist/types/server.react-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9324dd03a6d29030f72994732b8e37ca44385c2d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server.react-server.d.ts @@ -0,0 +1 @@ +export * from './server/react-server/index.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-client/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-client/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcb139a50b2c37b8d72b4f6c9a1be8e2e92a378d --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-client/index.d.ts @@ -0,0 +1,10 @@ +import type { getExtracted as getExtracted_type, getFormatter as getFormatter_type, getLocale as getLocale_type, getMessages as getMessages_type, getNow as getNow_type, getRequestConfig as getRequestConfig_type, getTimeZone as getTimeZone_type, setRequestLocale as setRequestLocale_type } from '../react-server/index.js'; +export declare function getRequestConfig(...args: Parameters): ReturnType; +export declare const getFormatter: typeof getFormatter_type; +export declare const getNow: typeof getNow_type; +export declare const getTimeZone: typeof getTimeZone_type; +export declare const getMessages: typeof getMessages_type; +export declare const getLocale: typeof getLocale_type; +export declare const getExtracted: typeof getExtracted_type; +export declare const getTranslations: () => never; +export declare const setRequestLocale: typeof setRequestLocale_type; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/RequestLocale.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/RequestLocale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a3812afd90fc0d6556c0a88fca20ccaa241e893 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/RequestLocale.d.ts @@ -0,0 +1 @@ +export declare function getRequestLocale(): Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/RequestLocaleCache.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/RequestLocaleCache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5813001c7b06e5f29ea56800e6994ec8160f001 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/RequestLocaleCache.d.ts @@ -0,0 +1,6 @@ +import type { Locale } from 'use-intl'; +export declare function getCachedRequestLocale(): string | undefined; +/** + * @deprecated Please migrate to [`next/root-params`](https://next-intl.dev/blog/nextjs-root-params). + */ +export declare function setCachedRequestLocale(locale: Locale): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/createRequestConfig.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/createRequestConfig.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d361be9bf4cd4fa4dbcf6fc5d6b17c794511fc27 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/createRequestConfig.d.ts @@ -0,0 +1,3 @@ +import type { GetRequestConfigParams, RequestConfig } from './getRequestConfig.js'; +declare const _default: (params: GetRequestConfigParams) => RequestConfig | Promise; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getConfig.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getConfig.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c021591e2df933b327e9f3ee1c3bb535acdd6094 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getConfig.d.ts @@ -0,0 +1,13 @@ +import { type IntlConfig, type Locale, _createIntlFormatters } from 'use-intl/core'; +declare function getConfigImpl(localeOverride?: Locale): Promise<{ + locale: IntlConfig['locale']; + formats?: NonNullable; + timeZone: NonNullable; + onError: NonNullable; + getMessageFallback: NonNullable; + messages?: NonNullable; + now?: NonNullable; + _formatters: ReturnType; +}>; +declare const getConfig: typeof getConfigImpl; +export default getConfig; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getConfigNow.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getConfigNow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..881e18f60bef89b4c816982eee6f6a270de70a50 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getConfigNow.d.ts @@ -0,0 +1,4 @@ +import type { Locale } from 'use-intl'; +declare function getConfigNowImpl(locale?: Locale): Promise; +declare const getConfigNow: typeof getConfigNowImpl; +export default getConfigNow; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getDefaultNow.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getDefaultNow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82dc8b2120cfeaa8b98f6bfaebf93a6cf01e27af --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getDefaultNow.d.ts @@ -0,0 +1,3 @@ +declare function defaultNow(): Date; +declare const getDefaultNow: typeof defaultNow; +export default getDefaultNow; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getExtracted.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getExtracted.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb414f811ed6b9bcc1f850c22b530bd8c2b23acb --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getExtracted.d.ts @@ -0,0 +1,10 @@ +import type { Locale } from 'use-intl/core'; +import getServerExtractor from './getServerExtractor.js'; +type Return = ReturnType; +declare function getExtractedImpl(namespace?: string): Promise; +declare function getExtractedImpl(opts?: { + locale: Locale; + namespace?: string; +}): Promise; +declare const getExtracted: typeof getExtractedImpl; +export default getExtracted; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getFormats.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getFormats.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcf18289617793c317e5765a6ac54a160cd7c1c6 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getFormats.d.ts @@ -0,0 +1,3 @@ +declare function getFormatsCachedImpl(): Promise; +declare const getFormats: typeof getFormatsCachedImpl; +export default getFormats; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getFormatter.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getFormatter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b01e615ee0a304f802d15c3676c04cae841697b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getFormatter.d.ts @@ -0,0 +1,10 @@ +import type { Locale, createFormatter } from 'use-intl/core'; +/** + * Returns a formatter based on the given locale. + * + * The formatter automatically receives the request config, but + * you can override it by passing in additional options. + */ +export default function getFormatter(opts?: { + locale?: Locale; +}): Promise>; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getLocale.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getLocale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ecba5ffb4bf14f378e56148a0b4ba7431afdee0 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getLocale.d.ts @@ -0,0 +1,4 @@ +import type { Locale } from 'use-intl'; +declare function getLocaleCachedImpl(): Promise; +declare const getLocaleCached: typeof getLocaleCachedImpl; +export default getLocaleCached; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getMessages.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getMessages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e03c4dc0a401b5786bf511c3d6ea63cd513f6f11 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getMessages.d.ts @@ -0,0 +1,6 @@ +import type { Locale, useMessages as useMessagesType } from 'use-intl'; +import getConfig from './getConfig.js'; +export declare function getMessagesFromConfig(config: Awaited>): ReturnType; +export default function getMessages(opts?: { + locale?: Locale; +}): Promise>; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getNow.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getNow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd6c56437239411e7c8374f29f454d0d836a26f9 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getNow.d.ts @@ -0,0 +1,4 @@ +import type { Locale } from 'use-intl'; +export default function getNow(opts?: { + locale?: Locale; +}): Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getRequestConfig.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getRequestConfig.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2deca09d3b0187f1e995ec6806b7b9060e4a9899 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getRequestConfig.d.ts @@ -0,0 +1,36 @@ +import type { IntlConfig, Locale } from 'use-intl/core'; +export type RequestConfig = Omit & { + /** + * @see https://next-intl.dev/docs/usage/configuration#i18n-request + **/ + locale: IntlConfig['locale']; +}; +export type GetRequestConfigParams = { + /** + * If you provide an explicit locale to an async server-side function like + * `getTranslations({locale: 'en'})`, it will be passed via `locale` to + * `getRequestConfig` so you can use it instead of the segment value. + */ + locale?: Locale; + /** + * Typically corresponds to the `[locale]` segment that was matched by the middleware. + * + * However, there are three special cases to consider: + * 1. **Overrides**: When an explicit `locale` is passed to awaitable functions + * like `getTranslations({locale: 'en'})`, then this value will be used + * instead of the segment. + * 2. **`undefined`**: The value can be `undefined` when a page outside of the + * `[locale]` segment renders (e.g. a language selection page at `app/page.tsx`). + * 3. **Invalid values**: Since the `[locale]` segment effectively acts like a + * catch-all for unknown routes (e.g. `/unknown.txt`), invalid values should + * be replaced with a valid locale. + * + * @deprecated Please migrate to [`next/root-params`](https://next-intl.dev/blog/nextjs-root-params). + * @see https://next-intl.dev/docs/usage/configuration#i18n-request + */ + requestLocale: Promise; +}; +/** + * Should be called in `i18n/request.ts` to create the configuration for the current request. + */ +export default function getRequestConfig(createRequestConfig: (params: GetRequestConfigParams) => RequestConfig | Promise): (params: GetRequestConfigParams) => RequestConfig | Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerExtractor.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerExtractor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc0883df1d066cf6226c07701a8800dd1da78e18 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerExtractor.d.ts @@ -0,0 +1,5 @@ +import type { createTranslator } from 'use-intl/core'; +import type { _useExtracted as useExtractedType } from 'use-intl/react'; +declare function getServerExtractorImpl(config: Parameters[0], namespace?: string): ReturnType; +declare const _default: typeof getServerExtractorImpl; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerFormatter.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerFormatter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..735af361a87f008c15aaed8acfee729604e07ee5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerFormatter.d.ts @@ -0,0 +1,29 @@ +import { createFormatter } from 'use-intl/core'; +declare function getFormatterCachedImpl(config: Parameters[0]): { + dateTime: { + (value: Date | number, options?: import("use-intl/core").DateTimeFormatOptions): string; + (value: Date | number, format?: string, options?: import("use-intl/core").DateTimeFormatOptions): string; + }; + number: { + (value: number | bigint, options?: import("use-intl/core").NumberFormatOptions): string; + (value: number | bigint, format?: string, options?: import("use-intl/core").NumberFormatOptions): string; + }; + relativeTime: { + (date: number | Date, now?: import("use-intl/core").RelativeTimeFormatOptions["now"]): string; + (date: number | Date, options?: import("use-intl/core").RelativeTimeFormatOptions): string; + }; + list: { + >>(value: Iterable, options?: Intl.ListFormatOptions): Value extends string ? string : Iterable; + >>(value: Iterable, format?: string, options?: Intl.ListFormatOptions): Value extends string ? string : Iterable; + }; + dateTimeRange: { + (start: Date | number, end: Date | number, options?: import("use-intl/core").DateTimeFormatOptions): string; + (start: Date | number, end: Date | number, format?: string, options?: import("use-intl/core").DateTimeFormatOptions): string; + }; + displayName: { + (value: string, options: Intl.DisplayNamesOptions): string; + (value: string, format: string, options?: Intl.DisplayNamesOptions): string; + }; +}; +declare const getFormatterCached: typeof getFormatterCachedImpl; +export default getFormatterCached; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerTranslator.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerTranslator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff1f968508c6cd8c9aaac5a043c080d19152053b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getServerTranslator.d.ts @@ -0,0 +1,4 @@ +import { type Messages, type NamespaceKeys, type NestedKeyOf, createTranslator } from 'use-intl/core'; +declare function getServerTranslatorImpl> = never>(config: Parameters[0], namespace?: NestedKey): ReturnType>; +declare const _default: typeof getServerTranslatorImpl; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getTimeZone.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getTimeZone.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4632025350ff761288159c3365dcbe69d9ab618f --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getTimeZone.d.ts @@ -0,0 +1,4 @@ +import type { Locale, Timezone } from 'use-intl'; +export default function getTimeZone(opts?: { + locale?: Locale; +}): Promise; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/getTranslations.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getTranslations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee4306d4d6d0493479a38842a6414d7963e7708a --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/getTranslations.d.ts @@ -0,0 +1,8 @@ +import type { Locale, Messages, NamespaceKeys, NestedKeyOf, createTranslator } from 'use-intl/core'; +declare function getTranslations> = never>(namespace?: NestedKey): Promise>>; +declare function getTranslations> = never>(opts?: { + locale: Locale; + namespace?: NestedKey; +}): Promise>>; +declare const _default: typeof getTranslations; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/index.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b5be9b1af84d3a1cdb863f15b2c99d74563b729 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/index.d.ts @@ -0,0 +1,12 @@ +/** + * Server-only APIs available via `next-intl/server`. + */ +export { default as getRequestConfig, type GetRequestConfigParams, type RequestConfig } from './getRequestConfig.js'; +export { default as getFormatter } from './getFormatter.js'; +export { default as getNow } from './getNow.js'; +export { default as getTimeZone } from './getTimeZone.js'; +export { default as getTranslations } from './getTranslations.js'; +export { default as getExtracted } from './getExtracted.js'; +export { default as getMessages } from './getMessages.js'; +export { default as getLocale } from './getLocale.js'; +export { setCachedRequestLocale as setRequestLocale } from './RequestLocaleCache.js'; diff --git a/e-commerce/node_modules/next-intl/dist/types/server/react-server/validateLocale.d.ts b/e-commerce/node_modules/next-intl/dist/types/server/react-server/validateLocale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48e0fbbcdad0351ad35ec957fa6463f067087b64 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/server/react-server/validateLocale.d.ts @@ -0,0 +1 @@ +export default function validateLocale(locale: string): void; diff --git a/e-commerce/node_modules/next-intl/dist/types/shared/NextIntlClientProvider.d.ts b/e-commerce/node_modules/next-intl/dist/types/shared/NextIntlClientProvider.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5035393f183a6cde3f568c17daddc50ecf7e5186 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/shared/NextIntlClientProvider.d.ts @@ -0,0 +1,9 @@ +import type { ComponentProps } from 'react'; +import type { Locale } from 'use-intl'; +import { IntlProvider } from 'use-intl/react'; +type Props = Omit, 'locale'> & { + /** This is automatically received when being rendered from a Server Component. In all other cases, e.g. when rendered from a Client Component, a unit test or with the Pages Router, you can pass this prop explicitly. */ + locale?: Locale; +}; +export default function NextIntlClientProvider({ locale, ...rest }: Props): import("react/jsx-runtime").JSX.Element; +export {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/shared/constants.d.ts b/e-commerce/node_modules/next-intl/dist/types/shared/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce3d37f3abb98656035ed45a5afeada58022f7e9 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/shared/constants.d.ts @@ -0,0 +1 @@ +export declare const HEADER_LOCALE_NAME = "X-NEXT-INTL-LOCALE"; diff --git a/e-commerce/node_modules/next-intl/dist/types/shared/types.d.ts b/e-commerce/node_modules/next-intl/dist/types/shared/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a7e6414912542da7ec8793c7c669f1b72ff0384 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/shared/types.d.ts @@ -0,0 +1,5 @@ +export type ParametersExceptFirst = Fn extends (arg0: any, ...rest: infer R) => any ? R : never; +export type ParametersExceptFirstTwo = Fn extends (arg0: any, arg1: any, ...rest: infer R) => any ? R : never; +export type Prettify = { + [Key in keyof Type]: Type[Key]; +} & {}; diff --git a/e-commerce/node_modules/next-intl/dist/types/shared/use.d.ts b/e-commerce/node_modules/next-intl/dist/types/shared/use.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..831677ad430401d9e2f98137e7514ac441635202 --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/shared/use.d.ts @@ -0,0 +1,3 @@ +import * as react from 'react'; +declare const _default: typeof react.use; +export default _default; diff --git a/e-commerce/node_modules/next-intl/dist/types/shared/utils.d.ts b/e-commerce/node_modules/next-intl/dist/types/shared/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de161ad495e62bcc7ff9d40b3ea4ada6576cea9b --- /dev/null +++ b/e-commerce/node_modules/next-intl/dist/types/shared/utils.d.ts @@ -0,0 +1,20 @@ +import type { LinkProps } from 'next/link.js'; +import type { LocalePrefixConfigVerbose, LocalePrefixMode, Locales, Pathnames } from '../routing/types.js'; +type Href = LinkProps['href']; +export declare function isLocalizableHref(href: Href): boolean; +export declare function unprefixPathname(pathname: string, prefix: string): string; +export declare function prefixPathname(prefix: string, pathname: string): string; +export declare function hasPathnamePrefixed(prefix: string | undefined, pathname: string): boolean; +export declare function getLocalizedTemplate(pathnameConfig: Pathnames[keyof Pathnames], locale: AppLocales[number], internalTemplate: string): string; +export declare function normalizeTrailingSlash(pathname: string): string; +export declare function matchesPathname( +/** E.g. `/users/[userId]-[userName]` */ +template: string, +/** E.g. `/users/23-jane` */ +pathname: string): boolean; +export declare function getLocalePrefix(locale: AppLocales[number], localePrefix: LocalePrefixConfigVerbose): string; +export declare function getLocaleAsPrefix(locale: string): string; +export declare function templateToRegex(template: string): RegExp; +export declare function getSortedPathnames(pathnames: Array): string[]; +export declare function isPromise(value: Value | Promise): value is Promise; +export {}; diff --git a/e-commerce/node_modules/next-intl/extractor.d.ts b/e-commerce/node_modules/next-intl/extractor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c31d3c289300e2ae4866dbdf36b5ad7c6eac872 --- /dev/null +++ b/e-commerce/node_modules/next-intl/extractor.d.ts @@ -0,0 +1,2 @@ +// Needed for projects with `moduleResolution: 'node'` +export * from './dist/types/extractor'; diff --git a/e-commerce/node_modules/next-intl/extractor/catalogLoader.d.ts b/e-commerce/node_modules/next-intl/extractor/catalogLoader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..259128ae9a0db4f8eacbfaf6b91ad333999aec9c --- /dev/null +++ b/e-commerce/node_modules/next-intl/extractor/catalogLoader.d.ts @@ -0,0 +1,4 @@ +// Needed for projects with `moduleResolution: 'node'` +import catalogLoader from '../dist/types/plugin/catalog/catalogLoader.d.ts'; + +export default catalogLoader; diff --git a/e-commerce/node_modules/next-intl/extractor/extractionLoader.d.ts b/e-commerce/node_modules/next-intl/extractor/extractionLoader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9efbf13795e905c01ba83b8b00e73c8081e19e51 --- /dev/null +++ b/e-commerce/node_modules/next-intl/extractor/extractionLoader.d.ts @@ -0,0 +1,4 @@ +// Needed for projects with `moduleResolution: 'node'` +import extractionLoader from '../dist/types/plugin/extractor/extractionLoader.d.ts'; + +export default extractionLoader; diff --git a/e-commerce/node_modules/next-intl/middleware.d.ts b/e-commerce/node_modules/next-intl/middleware.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1067ba907ddb222e5ded11aeee33e9ad2379e854 --- /dev/null +++ b/e-commerce/node_modules/next-intl/middleware.d.ts @@ -0,0 +1,4 @@ +// Needed for projects with `moduleResolution: 'node'` +import createMiddleware from './dist/types/middleware'; + +export default createMiddleware; diff --git a/e-commerce/node_modules/next-intl/navigation.d.ts b/e-commerce/node_modules/next-intl/navigation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea19b24e0e36426fc8bc714b85ae791246ecc7cd --- /dev/null +++ b/e-commerce/node_modules/next-intl/navigation.d.ts @@ -0,0 +1,2 @@ +// Needed for projects with `moduleResolution: 'node'` +export * from './dist/types/navigation.react-client'; diff --git a/e-commerce/node_modules/next-intl/package.json b/e-commerce/node_modules/next-intl/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f8e35393de87fc388aaaf56ea723e1af68747e1a --- /dev/null +++ b/e-commerce/node_modules/next-intl/package.json @@ -0,0 +1,149 @@ +{ + "name": "next-intl", + "version": "4.14.9", + "sideEffects": false, + "author": "Jan Amann ", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/amannn" + } + ], + "description": "Internationalization (i18n) for Next.js", + "license": "MIT", + "homepage": "https://next-intl.dev", + "repository": { + "type": "git", + "url": "git+https://github.com/amannn/next-intl.git" + }, + "scripts": { + "build": "rm -rf dist && rollup -c", + "test": "TZ=Europe/Berlin vitest", + "lint": "pnpm run lint:source && pnpm run lint:package", + "lint:source": "eslint src test && tsc --noEmit && pnpm run lint:prettier", + "lint:package": "publint && attw --pack --ignore-rules=cjs-resolves-to-esm", + "lint:prettier": "prettier src --check", + "prepublishOnly": "turbo build && cp ../../README.md .", + "postpublish": "git checkout . && rm ./README.md", + "size": "size-limit" + }, + "type": "module", + "main": "./dist/esm/production/index.react-client.js", + "typings": "./dist/types/index.react-client.d.ts", + "exports": { + ".": { + "types": "./dist/types/index.react-client.d.ts", + "react-server": { + "development": "./dist/esm/development/index.react-server.js", + "default": "./dist/esm/production/index.react-server.js" + }, + "development": "./dist/esm/development/index.react-client.js", + "default": "./dist/esm/production/index.react-client.js" + }, + "./server": { + "types": "./dist/types/server.react-server.d.ts", + "react-server": { + "development": "./dist/esm/development/server.react-server.js", + "default": "./dist/esm/production/server.react-server.js" + }, + "development": "./dist/esm/development/server.react-client.js", + "default": "./dist/esm/production/server.react-client.js" + }, + "./config": { + "types": "./dist/types/config.d.ts", + "development": "./dist/esm/development/config.js", + "default": "./dist/esm/production/config.js" + }, + "./middleware": { + "types": "./dist/types/middleware.d.ts", + "development": "./dist/esm/development/middleware.js", + "default": "./dist/esm/production/middleware.js" + }, + "./navigation": { + "types": "./dist/types/navigation.react-client.d.ts", + "react-server": { + "development": "./dist/esm/development/navigation.react-server.js", + "default": "./dist/esm/production/navigation.react-server.js" + }, + "development": "./dist/esm/development/navigation.react-client.js", + "default": "./dist/esm/production/navigation.react-client.js" + }, + "./routing": { + "types": "./dist/types/routing.d.ts", + "development": "./dist/esm/development/routing.js", + "default": "./dist/esm/production/routing.js" + }, + "./plugin": { + "import": { + "types": "./dist/types/plugin.d.ts", + "development": "./dist/esm/development/plugin.js", + "default": "./dist/esm/production/plugin.js" + }, + "require": { + "types": "./plugin.d.cts", + "default": "./dist/cjs/development/plugin.cjs" + }, + "default": "./dist/esm/production/plugin.js" + }, + "./extractor": { + "types": "./dist/types/extractor.d.ts", + "default": "./dist/esm/production/extractor.js" + }, + "./extractor/extractionLoader": { + "types": "./dist/types/plugin/extractor/extractionLoader.d.ts", + "default": "./dist/esm/production/extractor/extractionLoader.js" + }, + "./extractor/catalogLoader": { + "types": "./dist/types/plugin/catalog/catalogLoader.d.ts", + "default": "./dist/esm/production/extractor/catalogLoader.js" + } + }, + "files": [ + "dist", + "extractor", + "server.d.ts", + "navigation.d.ts", + "middleware.d.ts", + "plugin.d.ts", + "plugin.d.cts", + "routing.d.ts", + "config.d.ts", + "extractor.d.ts" + ], + "keywords": [ + "react", + "intl", + "i18n", + "internationalization", + "localization", + "translate", + "translation", + "format", + "formatting", + "next", + "next.js" + ], + "dependencies": { + "@eloqnt/config": "^0.1.1", + "@eloqnt/format-json": "^0.1.0", + "@eloqnt/format-po": "^0.1.1", + "@formatjs/intl-localematcher": "^0.8.1", + "@parcel/watcher": "^2.4.1", + "@swc/core": "~1.16.0", + "icu-minify": "^4.14.9", + "negotiator": "^1.0.0", + "next-intl-swc-plugin-extractor": "4.14.9", + "use-intl": "^4.14.9" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "next": "^12.0.0 || ^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || >=19.0.0-rc <19.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + }, + "gitHead": "b9fc98a814957b9c97894c7b57151215ac39afa6" +} diff --git a/e-commerce/node_modules/next-intl/plugin.d.cts b/e-commerce/node_modules/next-intl/plugin.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..266baeabc16b52f8110b4d8967fab0cc85bc70c5 --- /dev/null +++ b/e-commerce/node_modules/next-intl/plugin.d.cts @@ -0,0 +1,3 @@ +import createNextIntlPlugin from './dist/types/plugin.ts'; + +export = createNextIntlPlugin; diff --git a/e-commerce/node_modules/next-intl/plugin.d.ts b/e-commerce/node_modules/next-intl/plugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d772a3f6d6d8cd2df31fce061b0b0c1f42d1fbd --- /dev/null +++ b/e-commerce/node_modules/next-intl/plugin.d.ts @@ -0,0 +1,4 @@ +// Needed for projects with `moduleResolution: 'node'` +import plugin from './dist/types/plugin'; + +export default plugin; diff --git a/e-commerce/node_modules/next-intl/routing.d.ts b/e-commerce/node_modules/next-intl/routing.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..51815e313b6f3ae967c989d8332676b9961e74a6 --- /dev/null +++ b/e-commerce/node_modules/next-intl/routing.d.ts @@ -0,0 +1,2 @@ +// Needed for projects with `moduleResolution: 'node'` +export * from './dist/types/routing'; diff --git a/e-commerce/node_modules/next-intl/server.d.ts b/e-commerce/node_modules/next-intl/server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0a7dc88418fb73486f2511da3f9d174f7b11616 --- /dev/null +++ b/e-commerce/node_modules/next-intl/server.d.ts @@ -0,0 +1,2 @@ +// Needed for projects with `moduleResolution: 'node'` +export * from './dist/types/server/react-server'; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05ebb0239cad47f214f4e1cc265d75ac5fbae0be --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.d.ts @@ -0,0 +1,3 @@ +import React from 'react'; +import type { NextRouter } from './router/router'; +export declare const RouterContext: React.Context; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..fa861beeba55d756d82b429191c99b0c5269b4e5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "RouterContext", { + enumerable: true, + get: function() { + return RouterContext; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _react = /*#__PURE__*/ _interop_require_default._(require("react")); +const RouterContext = _react.default.createContext(null); +if (process.env.NODE_ENV !== 'production') { + RouterContext.displayName = 'RouterContext'; +} + +//# sourceMappingURL=router-context.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..305e0597cd90f631b63fbc4eb97da97d94572562 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router-context.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/router-context.shared-runtime.ts"],"sourcesContent":["import React from 'react'\nimport type { NextRouter } from './router/router'\n\nexport const RouterContext = React.createContext(null)\n\nif (process.env.NODE_ENV !== 'production') {\n RouterContext.displayName = 'RouterContext'\n}\n"],"names":["RouterContext","React","createContext","process","env","NODE_ENV","displayName"],"mappings":";;;;+BAGaA;;;eAAAA;;;;gEAHK;AAGX,MAAMA,gBAAgBC,cAAK,CAACC,aAAa,CAAoB;AAEpE,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCL,cAAcM,WAAW,GAAG;AAC9B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..309b35232a731a3c2bdae2ba59f39628ea338635 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.d.ts @@ -0,0 +1,6 @@ +/** + * Similarly to `addPathPrefix`, this function adds a suffix at the end on the + * provided path. It also works only for paths ensuring the argument starts + * with a slash. + */ +export declare function addPathSuffix(path: string, suffix?: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js new file mode 100644 index 0000000000000000000000000000000000000000..a946497970dd5907645b2139a0241148de6aa5f8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "addPathSuffix", { + enumerable: true, + get: function() { + return addPathSuffix; + } +}); +const _parsepath = require("./parse-path"); +function addPathSuffix(path, suffix) { + if (!path.startsWith('/') || !suffix) { + return path; + } + const { pathname, query, hash } = (0, _parsepath.parsePath)(path); + return `${pathname}${suffix}${query}${hash}`; +} + +//# sourceMappingURL=add-path-suffix.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a75094a05caa2672b71eda27b1de29b5439f1bd1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/add-path-suffix.ts"],"sourcesContent":["import { parsePath } from './parse-path'\n\n/**\n * Similarly to `addPathPrefix`, this function adds a suffix at the end on the\n * provided path. It also works only for paths ensuring the argument starts\n * with a slash.\n */\nexport function addPathSuffix(path: string, suffix?: string) {\n if (!path.startsWith('/') || !suffix) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n return `${pathname}${suffix}${query}${hash}`\n}\n"],"names":["addPathSuffix","path","suffix","startsWith","pathname","query","hash","parsePath"],"mappings":";;;;+BAOgBA;;;eAAAA;;;2BAPU;AAOnB,SAASA,cAAcC,IAAY,EAAEC,MAAe;IACzD,IAAI,CAACD,KAAKE,UAAU,CAAC,QAAQ,CAACD,QAAQ;QACpC,OAAOD;IACT;IAEA,MAAM,EAAEG,QAAQ,EAAEC,KAAK,EAAEC,IAAI,EAAE,GAAGC,IAAAA,oBAAS,EAACN;IAC5C,OAAO,GAAGG,WAAWF,SAASG,QAAQC,MAAM;AAC9C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbf31ec217060d8695873714c87c17f171bdc44d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.d.ts @@ -0,0 +1,42 @@ +/** + * Normalizes an app route so it represents the actual request path. Essentially + * performing the following transformations: + * + * - `/(dashboard)/user/[id]/page` to `/user/[id]` + * - `/(dashboard)/account/page` to `/account` + * - `/user/[id]/page` to `/user/[id]` + * - `/account/page` to `/account` + * - `/page` to `/` + * - `/(dashboard)/user/[id]/route` to `/user/[id]` + * - `/(dashboard)/account/route` to `/account` + * - `/user/[id]/route` to `/user/[id]` + * - `/account/route` to `/account` + * - `/route` to `/` + * - `/` to `/` + * + * @param route the app route to normalize + * @returns the normalized pathname + */ +export declare function normalizeAppPath(route: string): string; +/** + * Comparator for sorting app paths so that parallel slot paths (containing + * `/@`) come before the children/root page path. This keeps the direct + * children/root page last so it can be selected as the canonical entry. + * + * Without this, route group prefixes like `(group)` (char code 0x28) sort + * before `@` (0x40), causing the children page to sort first instead of last + * and leading to a manifest mismatch / 404 in webpack dev mode. + */ +export declare function compareAppPaths(a: string, b: string): number; +/** + * Selects the app path that owns the compiled entry for a normalized route. + * Catch-all normalization can add app paths from other routes, so only direct + * paths are candidates. Among those, compareAppPaths deterministically prefers + * the children/root page, or a stable slot when the route only has slots. + */ +export declare function selectAppPageEntry(pathname: string, appPaths: readonly string[], normalizePathname?: (appPath: string) => string): string; +/** + * Strips the `.rsc` extension if it's in the pathname. + * Since this function is used on full urls it checks `?` for searchParams handling. + */ +export declare function normalizeRscURL(url: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.js new file mode 100644 index 0000000000000000000000000000000000000000..333b45874f5b96e321a223dce213ec8f35a1ebd3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.js @@ -0,0 +1,84 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + compareAppPaths: null, + normalizeAppPath: null, + normalizeRscURL: null, + selectAppPageEntry: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + compareAppPaths: function() { + return compareAppPaths; + }, + normalizeAppPath: function() { + return normalizeAppPath; + }, + normalizeRscURL: function() { + return normalizeRscURL; + }, + selectAppPageEntry: function() { + return selectAppPageEntry; + } +}); +const _ensureleadingslash = require("../../page-path/ensure-leading-slash"); +const _segment = require("../../segment"); +function normalizeAppPath(route) { + return (0, _ensureleadingslash.ensureLeadingSlash)(route.split('/').reduce((pathname, segment, index, segments)=>{ + // Empty segments are ignored. + if (!segment) { + return pathname; + } + // Groups are ignored. + if ((0, _segment.isGroupSegment)(segment)) { + return pathname; + } + // Parallel segments are ignored. + if (segment[0] === '@') { + return pathname; + } + // The last segment (if it's a leaf) should be ignored. + if ((segment === 'page' || segment === 'route') && index === segments.length - 1) { + return pathname; + } + return `${pathname}/${segment}`; + }, '')); +} +function compareAppPaths(a, b) { + const aHasSlot = a.includes('/@'); + const bHasSlot = b.includes('/@'); + if (aHasSlot && !bHasSlot) return -1; + if (!aHasSlot && bHasSlot) return 1; + return a.localeCompare(b); +} +function normalizeAppPageEntryPathname(appPath) { + // Webpack app entries preserve escaped underscore segments as `%5F`, while + // normalized request pathnames expose the decoded `_` segment. + return normalizeAppPath(appPath).replace(/%5F/g, '_'); +} +function selectAppPageEntry(pathname, appPaths, normalizePathname = normalizeAppPageEntryPathname) { + let entry; + for (const appPath of appPaths){ + if (normalizePathname(appPath) !== pathname) continue; + if (entry === undefined || compareAppPaths(entry, appPath) < 0) { + entry = appPath; + } + } + if (entry === undefined) { + throw new Error(`Invariant: no direct app page entry found for ${pathname}`); + } + return entry; +} +function normalizeRscURL(url) { + return url.replace(/\.rsc($|\?)/, // $1 ensures `?` is preserved + '$1'); +} + +//# sourceMappingURL=app-paths.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a3e133e8f2019e20ee9fe38144dc593fda631fb7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/app-paths.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/app-paths.ts"],"sourcesContent":["import { ensureLeadingSlash } from '../../page-path/ensure-leading-slash'\nimport { isGroupSegment } from '../../segment'\n\n/**\n * Normalizes an app route so it represents the actual request path. Essentially\n * performing the following transformations:\n *\n * - `/(dashboard)/user/[id]/page` to `/user/[id]`\n * - `/(dashboard)/account/page` to `/account`\n * - `/user/[id]/page` to `/user/[id]`\n * - `/account/page` to `/account`\n * - `/page` to `/`\n * - `/(dashboard)/user/[id]/route` to `/user/[id]`\n * - `/(dashboard)/account/route` to `/account`\n * - `/user/[id]/route` to `/user/[id]`\n * - `/account/route` to `/account`\n * - `/route` to `/`\n * - `/` to `/`\n *\n * @param route the app route to normalize\n * @returns the normalized pathname\n */\nexport function normalizeAppPath(route: string) {\n return ensureLeadingSlash(\n route.split('/').reduce((pathname, segment, index, segments) => {\n // Empty segments are ignored.\n if (!segment) {\n return pathname\n }\n\n // Groups are ignored.\n if (isGroupSegment(segment)) {\n return pathname\n }\n\n // Parallel segments are ignored.\n if (segment[0] === '@') {\n return pathname\n }\n\n // The last segment (if it's a leaf) should be ignored.\n if (\n (segment === 'page' || segment === 'route') &&\n index === segments.length - 1\n ) {\n return pathname\n }\n\n return `${pathname}/${segment}`\n }, '')\n )\n}\n\n/**\n * Comparator for sorting app paths so that parallel slot paths (containing\n * `/@`) come before the children/root page path. This keeps the direct\n * children/root page last so it can be selected as the canonical entry.\n *\n * Without this, route group prefixes like `(group)` (char code 0x28) sort\n * before `@` (0x40), causing the children page to sort first instead of last\n * and leading to a manifest mismatch / 404 in webpack dev mode.\n */\nexport function compareAppPaths(a: string, b: string): number {\n const aHasSlot = a.includes('/@')\n const bHasSlot = b.includes('/@')\n if (aHasSlot && !bHasSlot) return -1\n if (!aHasSlot && bHasSlot) return 1\n return a.localeCompare(b)\n}\n\nfunction normalizeAppPageEntryPathname(appPath: string): string {\n // Webpack app entries preserve escaped underscore segments as `%5F`, while\n // normalized request pathnames expose the decoded `_` segment.\n return normalizeAppPath(appPath).replace(/%5F/g, '_')\n}\n\n/**\n * Selects the app path that owns the compiled entry for a normalized route.\n * Catch-all normalization can add app paths from other routes, so only direct\n * paths are candidates. Among those, compareAppPaths deterministically prefers\n * the children/root page, or a stable slot when the route only has slots.\n */\nexport function selectAppPageEntry(\n pathname: string,\n appPaths: readonly string[],\n normalizePathname: (appPath: string) => string = normalizeAppPageEntryPathname\n): string {\n let entry: string | undefined\n\n for (const appPath of appPaths) {\n if (normalizePathname(appPath) !== pathname) continue\n\n if (entry === undefined || compareAppPaths(entry, appPath) < 0) {\n entry = appPath\n }\n }\n\n if (entry === undefined) {\n throw new Error(`Invariant: no direct app page entry found for ${pathname}`)\n }\n\n return entry\n}\n\n/**\n * Strips the `.rsc` extension if it's in the pathname.\n * Since this function is used on full urls it checks `?` for searchParams handling.\n */\nexport function normalizeRscURL(url: string) {\n return url.replace(\n /\\.rsc($|\\?)/,\n // $1 ensures `?` is preserved\n '$1'\n )\n}\n"],"names":["compareAppPaths","normalizeAppPath","normalizeRscURL","selectAppPageEntry","route","ensureLeadingSlash","split","reduce","pathname","segment","index","segments","isGroupSegment","length","a","b","aHasSlot","includes","bHasSlot","localeCompare","normalizeAppPageEntryPathname","appPath","replace","appPaths","normalizePathname","entry","undefined","Error","url"],"mappings":";;;;;;;;;;;;;;;;;IA8DgBA,eAAe;eAAfA;;IAxCAC,gBAAgB;eAAhBA;;IAsFAC,eAAe;eAAfA;;IA1BAC,kBAAkB;eAAlBA;;;oCAlFmB;yBACJ;AAqBxB,SAASF,iBAAiBG,KAAa;IAC5C,OAAOC,IAAAA,sCAAkB,EACvBD,MAAME,KAAK,CAAC,KAAKC,MAAM,CAAC,CAACC,UAAUC,SAASC,OAAOC;QACjD,8BAA8B;QAC9B,IAAI,CAACF,SAAS;YACZ,OAAOD;QACT;QAEA,sBAAsB;QACtB,IAAII,IAAAA,uBAAc,EAACH,UAAU;YAC3B,OAAOD;QACT;QAEA,iCAAiC;QACjC,IAAIC,OAAO,CAAC,EAAE,KAAK,KAAK;YACtB,OAAOD;QACT;QAEA,uDAAuD;QACvD,IACE,AAACC,CAAAA,YAAY,UAAUA,YAAY,OAAM,KACzCC,UAAUC,SAASE,MAAM,GAAG,GAC5B;YACA,OAAOL;QACT;QAEA,OAAO,GAAGA,SAAS,CAAC,EAAEC,SAAS;IACjC,GAAG;AAEP;AAWO,SAAST,gBAAgBc,CAAS,EAAEC,CAAS;IAClD,MAAMC,WAAWF,EAAEG,QAAQ,CAAC;IAC5B,MAAMC,WAAWH,EAAEE,QAAQ,CAAC;IAC5B,IAAID,YAAY,CAACE,UAAU,OAAO,CAAC;IACnC,IAAI,CAACF,YAAYE,UAAU,OAAO;IAClC,OAAOJ,EAAEK,aAAa,CAACJ;AACzB;AAEA,SAASK,8BAA8BC,OAAe;IACpD,2EAA2E;IAC3E,+DAA+D;IAC/D,OAAOpB,iBAAiBoB,SAASC,OAAO,CAAC,QAAQ;AACnD;AAQO,SAASnB,mBACdK,QAAgB,EAChBe,QAA2B,EAC3BC,oBAAiDJ,6BAA6B;IAE9E,IAAIK;IAEJ,KAAK,MAAMJ,WAAWE,SAAU;QAC9B,IAAIC,kBAAkBH,aAAab,UAAU;QAE7C,IAAIiB,UAAUC,aAAa1B,gBAAgByB,OAAOJ,WAAW,GAAG;YAC9DI,QAAQJ;QACV;IACF;IAEA,IAAII,UAAUC,WAAW;QACvB,MAAM,IAAIC,MAAM,CAAC,8CAA8C,EAAEnB,UAAU;IAC7E;IAEA,OAAOiB;AACT;AAMO,SAASvB,gBAAgB0B,GAAW;IACzC,OAAOA,IAAIN,OAAO,CAChB,eACA,8BAA8B;IAC9B;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c875acd90cb0a9bd278b67985dba73665989905 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.d.ts @@ -0,0 +1 @@ +export declare function asPathToSearchParams(asPath: string): URLSearchParams; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js new file mode 100644 index 0000000000000000000000000000000000000000..80d01c2d8fb855fe83fcd326f8cb0900e8be9f94 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js @@ -0,0 +1,17 @@ +// Convert router.asPath to a URLSearchParams object +// example: /dynamic/[slug]?foo=bar -> { foo: 'bar' } +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "asPathToSearchParams", { + enumerable: true, + get: function() { + return asPathToSearchParams; + } +}); +function asPathToSearchParams(asPath) { + return new URL(asPath, 'http://n').searchParams; +} + +//# sourceMappingURL=as-path-to-search-params.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js.map new file mode 100644 index 0000000000000000000000000000000000000000..05a3316ba983af790e00aff0d217be65157042c1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/as-path-to-search-params.ts"],"sourcesContent":["// Convert router.asPath to a URLSearchParams object\n// example: /dynamic/[slug]?foo=bar -> { foo: 'bar' }\nexport function asPathToSearchParams(asPath: string): URLSearchParams {\n return new URL(asPath, 'http://n').searchParams\n}\n"],"names":["asPathToSearchParams","asPath","URL","searchParams"],"mappings":"AAAA,oDAAoD;AACpD,qDAAqD;;;;;+BACrCA;;;eAAAA;;;AAAT,SAASA,qBAAqBC,MAAc;IACjD,OAAO,IAAIC,IAAID,QAAQ,YAAYE,YAAY;AACjD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..981a56baee92e9d4c4529661a4a85af313a05de1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.d.ts @@ -0,0 +1,2 @@ +export declare function computeCacheBustingSearchParam(prefetchHeader: '1' | '2' | '3' | '0' | undefined, segmentPrefetchHeader: string | string[] | undefined, stateTreeHeader: string | string[] | undefined, nextUrlHeader: string | string[] | undefined): Promise; +export declare function computeLegacyCacheBustingSearchParam(prefetchHeader: '1' | '2' | '3' | '0' | undefined, segmentPrefetchHeader: string | string[] | undefined, stateTreeHeader: string | string[] | undefined, nextUrlHeader: string | string[] | undefined): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.js new file mode 100644 index 0000000000000000000000000000000000000000..56f48aae97ddc0a18261bad5d42067b6798d01c2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + computeCacheBustingSearchParam: null, + computeLegacyCacheBustingSearchParam: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + computeCacheBustingSearchParam: function() { + return computeCacheBustingSearchParam; + }, + computeLegacyCacheBustingSearchParam: function() { + return computeLegacyCacheBustingSearchParam; + } +}); +const _hash = require("../../hash"); +const CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12; +const textEncoder = new TextEncoder(); +function encodeCacheBustingSearchParam(bytes) { + let binary = ''; + for(let i = 0; i < bytes.length; i++){ + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +function normalizeCacheBustingInput(value) { + if (value === undefined) { + return '0'; + } + return Array.isArray(value) ? value.join(',') : value; +} +function createCacheBustingSearchParamInput(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader) { + if ((prefetchHeader === undefined || prefetchHeader === '0') && segmentPrefetchHeader === undefined && stateTreeHeader === undefined && nextUrlHeader === undefined) { + return null; + } + return [ + prefetchHeader ?? '0', + normalizeCacheBustingInput(segmentPrefetchHeader), + normalizeCacheBustingInput(stateTreeHeader), + normalizeCacheBustingInput(nextUrlHeader) + ].join(','); +} +async function computeCacheBustingSearchParamFromInput(input) { + // Truncate SHA-256 to 96 bits to keep `_rsc` compact + const digest = await globalThis.crypto.subtle.digest('SHA-256', textEncoder.encode(input)); + return encodeCacheBustingSearchParam(new Uint8Array(digest).subarray(0, CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES)); +} +async function computeCacheBustingSearchParam(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader) { + const input = createCacheBustingSearchParamInput(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader); + if (input === null) { + return ''; + } + return computeCacheBustingSearchParamFromInput(input); +} +function computeLegacyCacheBustingSearchParam(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader) { + const input = createCacheBustingSearchParamInput(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader); + if (input === null) { + return ''; + } + return (0, _hash.hexHash)(input); +} + +//# sourceMappingURL=cache-busting-search-param.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2f135b3d4f490e895eb0dd8e449d5956235bbfce --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/cache-busting-search-param.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/cache-busting-search-param.ts"],"sourcesContent":["import { hexHash } from '../../hash'\n\nconst CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12\nconst textEncoder = new TextEncoder()\n\nfunction encodeCacheBustingSearchParam(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction normalizeCacheBustingInput(\n value: string | string[] | undefined\n): string {\n if (value === undefined) {\n return '0'\n }\n return Array.isArray(value) ? value.join(',') : value\n}\n\nfunction createCacheBustingSearchParamInput(\n prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): string | null {\n if (\n (prefetchHeader === undefined || prefetchHeader === '0') &&\n segmentPrefetchHeader === undefined &&\n stateTreeHeader === undefined &&\n nextUrlHeader === undefined\n ) {\n return null\n }\n\n return [\n prefetchHeader ?? '0',\n normalizeCacheBustingInput(segmentPrefetchHeader),\n normalizeCacheBustingInput(stateTreeHeader),\n normalizeCacheBustingInput(nextUrlHeader),\n ].join(',')\n}\n\nasync function computeCacheBustingSearchParamFromInput(\n input: string\n): Promise {\n // Truncate SHA-256 to 96 bits to keep `_rsc` compact\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n textEncoder.encode(input)\n )\n return encodeCacheBustingSearchParam(\n new Uint8Array(digest).subarray(0, CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES)\n )\n}\n\nexport async function computeCacheBustingSearchParam(\n prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): Promise {\n const input = createCacheBustingSearchParamInput(\n prefetchHeader,\n segmentPrefetchHeader,\n stateTreeHeader,\n nextUrlHeader\n )\n if (input === null) {\n return ''\n }\n\n return computeCacheBustingSearchParamFromInput(input)\n}\n\nexport function computeLegacyCacheBustingSearchParam(\n prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): string {\n const input = createCacheBustingSearchParamInput(\n prefetchHeader,\n segmentPrefetchHeader,\n stateTreeHeader,\n nextUrlHeader\n )\n if (input === null) {\n return ''\n }\n\n return hexHash(input)\n}\n"],"names":["computeCacheBustingSearchParam","computeLegacyCacheBustingSearchParam","CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES","textEncoder","TextEncoder","encodeCacheBustingSearchParam","bytes","binary","i","length","String","fromCharCode","btoa","replace","normalizeCacheBustingInput","value","undefined","Array","isArray","join","createCacheBustingSearchParamInput","prefetchHeader","segmentPrefetchHeader","stateTreeHeader","nextUrlHeader","computeCacheBustingSearchParamFromInput","input","digest","globalThis","crypto","subtle","encode","Uint8Array","subarray","hexHash"],"mappings":";;;;;;;;;;;;;;;IA2DsBA,8BAA8B;eAA9BA;;IAmBNC,oCAAoC;eAApCA;;;sBA9EQ;AAExB,MAAMC,0CAA0C;AAChD,MAAMC,cAAc,IAAIC;AAExB,SAASC,8BAA8BC,KAAiB;IACtD,IAAIC,SAAS;IACb,IAAK,IAAIC,IAAI,GAAGA,IAAIF,MAAMG,MAAM,EAAED,IAAK;QACrCD,UAAUG,OAAOC,YAAY,CAACL,KAAK,CAACE,EAAE;IACxC;IAEA,OAAOI,KAAKL,QAAQM,OAAO,CAAC,OAAO,KAAKA,OAAO,CAAC,OAAO,KAAKA,OAAO,CAAC,OAAO;AAC7E;AAEA,SAASC,2BACPC,KAAoC;IAEpC,IAAIA,UAAUC,WAAW;QACvB,OAAO;IACT;IACA,OAAOC,MAAMC,OAAO,CAACH,SAASA,MAAMI,IAAI,CAAC,OAAOJ;AAClD;AAEA,SAASK,mCACPC,cAAiD,EACjDC,qBAAoD,EACpDC,eAA8C,EAC9CC,aAA4C;IAE5C,IACE,AAACH,CAAAA,mBAAmBL,aAAaK,mBAAmB,GAAE,KACtDC,0BAA0BN,aAC1BO,oBAAoBP,aACpBQ,kBAAkBR,WAClB;QACA,OAAO;IACT;IAEA,OAAO;QACLK,kBAAkB;QAClBP,2BAA2BQ;QAC3BR,2BAA2BS;QAC3BT,2BAA2BU;KAC5B,CAACL,IAAI,CAAC;AACT;AAEA,eAAeM,wCACbC,KAAa;IAEb,qDAAqD;IACrD,MAAMC,SAAS,MAAMC,WAAWC,MAAM,CAACC,MAAM,CAACH,MAAM,CAClD,WACAxB,YAAY4B,MAAM,CAACL;IAErB,OAAOrB,8BACL,IAAI2B,WAAWL,QAAQM,QAAQ,CAAC,GAAG/B;AAEvC;AAEO,eAAeF,+BACpBqB,cAAiD,EACjDC,qBAAoD,EACpDC,eAA8C,EAC9CC,aAA4C;IAE5C,MAAME,QAAQN,mCACZC,gBACAC,uBACAC,iBACAC;IAEF,IAAIE,UAAU,MAAM;QAClB,OAAO;IACT;IAEA,OAAOD,wCAAwCC;AACjD;AAEO,SAASzB,qCACdoB,cAAiD,EACjDC,qBAAoD,EACpDC,eAA8C,EAC9CC,aAA4C;IAE5C,MAAME,QAAQN,mCACZC,gBACAC,uBACAC,iBACAC;IAEF,IAAIE,UAAU,MAAM;QAClB,OAAO;IACT;IAEA,OAAOQ,IAAAA,aAAO,EAACR;AACjB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4c405a297f1fa22fc06adce28761df28872214f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.d.ts @@ -0,0 +1,2 @@ +import type { default as Router } from '../router'; +export declare function compareRouterStates(a: Router['state'], b: Router['state']): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.js new file mode 100644 index 0000000000000000000000000000000000000000..18c6ec6f8c197ac0cbd1ea64c2466e1dee84e5c8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "compareRouterStates", { + enumerable: true, + get: function() { + return compareRouterStates; + } +}); +function compareRouterStates(a, b) { + const stateKeys = Object.keys(a); + if (stateKeys.length !== Object.keys(b).length) return false; + for(let i = stateKeys.length; i--;){ + const key = stateKeys[i]; + if (key === 'query') { + const queryKeys = Object.keys(a.query); + if (queryKeys.length !== Object.keys(b.query).length) { + return false; + } + for(let j = queryKeys.length; j--;){ + const queryKey = queryKeys[j]; + if (!b.query.hasOwnProperty(queryKey) || a.query[queryKey] !== b.query[queryKey]) { + return false; + } + } + } else if (!b.hasOwnProperty(key) || a[key] !== b[key]) { + return false; + } + } + return true; +} + +//# sourceMappingURL=compare-states.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f26f14b0f9ca804c0e5d8c335c0ffe70807acccd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/compare-states.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/compare-states.ts"],"sourcesContent":["import type { default as Router } from '../router'\n\nexport function compareRouterStates(a: Router['state'], b: Router['state']) {\n const stateKeys = Object.keys(a)\n if (stateKeys.length !== Object.keys(b).length) return false\n\n for (let i = stateKeys.length; i--; ) {\n const key = stateKeys[i]\n if (key === 'query') {\n const queryKeys = Object.keys(a.query)\n if (queryKeys.length !== Object.keys(b.query).length) {\n return false\n }\n for (let j = queryKeys.length; j--; ) {\n const queryKey = queryKeys[j]\n if (\n !b.query.hasOwnProperty(queryKey) ||\n a.query[queryKey] !== b.query[queryKey]\n ) {\n return false\n }\n }\n } else if (\n !b.hasOwnProperty(key) ||\n a[key as keyof Router['state']] !== b[key as keyof Router['state']]\n ) {\n return false\n }\n }\n\n return true\n}\n"],"names":["compareRouterStates","a","b","stateKeys","Object","keys","length","i","key","queryKeys","query","j","queryKey","hasOwnProperty"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAAT,SAASA,oBAAoBC,CAAkB,EAAEC,CAAkB;IACxE,MAAMC,YAAYC,OAAOC,IAAI,CAACJ;IAC9B,IAAIE,UAAUG,MAAM,KAAKF,OAAOC,IAAI,CAACH,GAAGI,MAAM,EAAE,OAAO;IAEvD,IAAK,IAAIC,IAAIJ,UAAUG,MAAM,EAAEC,KAAO;QACpC,MAAMC,MAAML,SAAS,CAACI,EAAE;QACxB,IAAIC,QAAQ,SAAS;YACnB,MAAMC,YAAYL,OAAOC,IAAI,CAACJ,EAAES,KAAK;YACrC,IAAID,UAAUH,MAAM,KAAKF,OAAOC,IAAI,CAACH,EAAEQ,KAAK,EAAEJ,MAAM,EAAE;gBACpD,OAAO;YACT;YACA,IAAK,IAAIK,IAAIF,UAAUH,MAAM,EAAEK,KAAO;gBACpC,MAAMC,WAAWH,SAAS,CAACE,EAAE;gBAC7B,IACE,CAACT,EAAEQ,KAAK,CAACG,cAAc,CAACD,aACxBX,EAAES,KAAK,CAACE,SAAS,KAAKV,EAAEQ,KAAK,CAACE,SAAS,EACvC;oBACA,OAAO;gBACT;YACF;QACF,OAAO,IACL,CAACV,EAAEW,cAAc,CAACL,QAClBP,CAAC,CAACO,IAA6B,KAAKN,CAAC,CAACM,IAA6B,EACnE;YACA,OAAO;QACT;IACF;IAEA,OAAO;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4337f89a801bf5a84ab212929c90f75e6ac32ab --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.d.ts @@ -0,0 +1,8 @@ +/** + * Run function with `scroll-behavior: auto` applied to ``. + * This css change will be reverted after the function finishes. + */ +export declare function disableSmoothScrollDuringRouteTransition(fn: () => void, options?: { + dontForceLayout?: boolean; + onlyHashChange?: boolean; +}): void; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.js new file mode 100644 index 0000000000000000000000000000000000000000..4d43a4969bf6fb144f7a3353e034afb329ad3b7a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.js @@ -0,0 +1,46 @@ +/** + * Run function with `scroll-behavior: auto` applied to ``. + * This css change will be reverted after the function finishes. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "disableSmoothScrollDuringRouteTransition", { + enumerable: true, + get: function() { + return disableSmoothScrollDuringRouteTransition; + } +}); +function disableSmoothScrollDuringRouteTransition(fn, options = {}) { + // if only the hash is changed, we don't need to disable smooth scrolling + // we only care to prevent smooth scrolling when navigating to a new page to avoid jarring UX + if (options.onlyHashChange) { + fn(); + return; + } + const htmlElement = document.documentElement; + const hasDataAttribute = htmlElement.dataset.scrollBehavior === 'smooth'; + if (!hasDataAttribute) { + // Warn if smooth scrolling is detected but no data attribute is present + if (process.env.NODE_ENV === 'development' && getComputedStyle(htmlElement).scrollBehavior === 'smooth') { + const { warnOnce } = require('../../utils/warn-once'); + warnOnce('Detected `scroll-behavior: smooth` on the `` element. To disable smooth scrolling during route transitions, ' + 'add `data-scroll-behavior="smooth"` to your element. ' + 'Learn more: https://nextjs.org/docs/messages/missing-data-scroll-behavior'); + } + // No smooth scrolling configured, run directly without style manipulation + fn(); + return; + } + // Proceed with temporarily disabling smooth scrolling + const existing = htmlElement.style.scrollBehavior; + htmlElement.style.scrollBehavior = 'auto'; + if (!options.dontForceLayout) { + // In Chrome-based browsers we need to force reflow before calling `scrollTo`. + // Otherwise it will not pickup the change in scrollBehavior + // More info here: https://github.com/vercel/next.js/issues/40719#issuecomment-1336248042 + htmlElement.getClientRects(); + } + fn(); + htmlElement.style.scrollBehavior = existing; +} + +//# sourceMappingURL=disable-smooth-scroll.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e64d6860ac343ac8a5d8c4827be66c2dc34da40c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/disable-smooth-scroll.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/disable-smooth-scroll.ts"],"sourcesContent":["/**\n * Run function with `scroll-behavior: auto` applied to ``.\n * This css change will be reverted after the function finishes.\n */\nexport function disableSmoothScrollDuringRouteTransition(\n fn: () => void,\n options: { dontForceLayout?: boolean; onlyHashChange?: boolean } = {}\n) {\n // if only the hash is changed, we don't need to disable smooth scrolling\n // we only care to prevent smooth scrolling when navigating to a new page to avoid jarring UX\n if (options.onlyHashChange) {\n fn()\n return\n }\n\n const htmlElement = document.documentElement\n const hasDataAttribute = htmlElement.dataset.scrollBehavior === 'smooth'\n\n if (!hasDataAttribute) {\n // Warn if smooth scrolling is detected but no data attribute is present\n if (\n process.env.NODE_ENV === 'development' &&\n getComputedStyle(htmlElement).scrollBehavior === 'smooth'\n ) {\n const { warnOnce } =\n require('../../utils/warn-once') as typeof import('../../utils/warn-once')\n warnOnce(\n 'Detected `scroll-behavior: smooth` on the `` element. To disable smooth scrolling during route transitions, ' +\n 'add `data-scroll-behavior=\"smooth\"` to your element. ' +\n 'Learn more: https://nextjs.org/docs/messages/missing-data-scroll-behavior'\n )\n }\n // No smooth scrolling configured, run directly without style manipulation\n fn()\n return\n }\n\n // Proceed with temporarily disabling smooth scrolling\n const existing = htmlElement.style.scrollBehavior\n htmlElement.style.scrollBehavior = 'auto'\n if (!options.dontForceLayout) {\n // In Chrome-based browsers we need to force reflow before calling `scrollTo`.\n // Otherwise it will not pickup the change in scrollBehavior\n // More info here: https://github.com/vercel/next.js/issues/40719#issuecomment-1336248042\n htmlElement.getClientRects()\n }\n fn()\n htmlElement.style.scrollBehavior = existing\n}\n"],"names":["disableSmoothScrollDuringRouteTransition","fn","options","onlyHashChange","htmlElement","document","documentElement","hasDataAttribute","dataset","scrollBehavior","process","env","NODE_ENV","getComputedStyle","warnOnce","require","existing","style","dontForceLayout","getClientRects"],"mappings":"AAAA;;;CAGC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,yCACdC,EAAc,EACdC,UAAmE,CAAC,CAAC;IAErE,yEAAyE;IACzE,6FAA6F;IAC7F,IAAIA,QAAQC,cAAc,EAAE;QAC1BF;QACA;IACF;IAEA,MAAMG,cAAcC,SAASC,eAAe;IAC5C,MAAMC,mBAAmBH,YAAYI,OAAO,CAACC,cAAc,KAAK;IAEhE,IAAI,CAACF,kBAAkB;QACrB,wEAAwE;QACxE,IACEG,QAAQC,GAAG,CAACC,QAAQ,KAAK,iBACzBC,iBAAiBT,aAAaK,cAAc,KAAK,UACjD;YACA,MAAM,EAAEK,QAAQ,EAAE,GAChBC,QAAQ;YACVD,SACE,uHACE,iEACA;QAEN;QACA,0EAA0E;QAC1Eb;QACA;IACF;IAEA,sDAAsD;IACtD,MAAMe,WAAWZ,YAAYa,KAAK,CAACR,cAAc;IACjDL,YAAYa,KAAK,CAACR,cAAc,GAAG;IACnC,IAAI,CAACP,QAAQgB,eAAe,EAAE;QAC5B,8EAA8E;QAC9E,4DAA4D;QAC5D,yFAAyF;QACzFd,YAAYe,cAAc;IAC5B;IACAlB;IACAG,YAAYa,KAAK,CAACR,cAAc,GAAGO;AACrC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57da7005a5404911ba5f9f8facc0881046a8c68b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.d.ts @@ -0,0 +1,25 @@ +/** + * A token that can never collide with a real path segment (dynamic segments are + * always `[name]`, `[...name]`, or `[[...name]]`, and static segments never + * equal `[]`). Shared with the builder's `normalizeRouteToFilterPattern`. + */ +export declare const DYNAMIC_FILTER_PLACEHOLDER = "[]"; +/** + * Test whether any app route that could shadow the resolved pages route passes + * `test` (typically a dynamic-filter membership check). An app route can only + * win over a matching pages route by turning some of that route's dynamic + * positions into static segments, so we enumerate keeping each such position + * either literal (static in the app route) or a placeholder (still dynamic in + * the app route) and return as soon as one passes. + * + * A static route segment pins its position to that literal; every other + * concrete position is dynamic and thus a candidate for a placeholder. That + * includes the tail a trailing catch-all (`[...slug]`/`[[...slug]]`) absorbs, + * which is why a catch-all route legitimately has fewer segments than the path + * it matched. + * + * Order is irrelevant: any match means the path is shadowed, and resolution is + * handed to the server via a hard navigation regardless of which candidate + * matched. + */ +export declare function hasDynamicFilterCandidate(routePattern: string, concretePathname: string, test: (candidate: string) => boolean): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..2c75215e2d6b33b300827ab4f8f199809ad7e1fb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.js @@ -0,0 +1,92 @@ +// The client router filter handles app routes that begin with a dynamic segment +// (e.g. `/[locale]/about`). Such routes have no static prefix to anchor the +// prefix-based dynamic filter on, so the build-time producer +// (`createClientRouterFilter`) stores them as a normalized pattern with dynamic +// segments replaced by the placeholder token below, and the pages router +// reconstructs matching candidates from the route it resolved a navigation to. +/** + * A token that can never collide with a real path segment (dynamic segments are + * always `[name]`, `[...name]`, or `[[...name]]`, and static segments never + * equal `[]`). Shared with the builder's `normalizeRouteToFilterPattern`. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DYNAMIC_FILTER_PLACEHOLDER: null, + hasDynamicFilterCandidate: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DYNAMIC_FILTER_PLACEHOLDER: function() { + return DYNAMIC_FILTER_PLACEHOLDER; + }, + hasDynamicFilterCandidate: function() { + return hasDynamicFilterCandidate; + } +}); +const DYNAMIC_FILTER_PLACEHOLDER = '[]'; +/** + * Beyond this many dynamic segments the 2^n candidate set is skipped. Real + * routes never approach this; the cap only guards against pathological input. + */ const MAX_DYNAMIC_SEGMENTS = 8; +function hasDynamicFilterCandidate(routePattern, concretePathname, test) { + const routeSegments = routePattern.split('/'); + const concreteSegments = concretePathname.split('/'); + const lastSegment = routeSegments[routeSegments.length - 1] ?? ''; + const hasCatchAll = lastSegment.startsWith('[...') || lastSegment.startsWith('[[...'); + // A non-catch-all route always has the same segment count as the path it + // matched; a mismatch there means the inputs don't line up. A catch-all route + // legitimately differs because its final param absorbs the remaining + // segments. + if (!hasCatchAll && routeSegments.length !== concreteSegments.length) { + return false; + } + // Collect the concrete positions that are dynamic in the matched route: any + // position without a static route segment (a dynamic param, or one absorbed + // by the trailing catch-all). + const dynamicIndices = []; + for(let i = 1; i < concreteSegments.length; i++){ + // An empty concrete segment is not a real path segment (splitting `/` + // yields a trailing `''`). A trailing optional catch-all matches it by + // absorbing nothing, so it must not be treated as a dynamic position: + // otherwise `/` would reconstruct the `/[]` candidate and spuriously match + // a root-level dynamic app route such as `/[lang]`, which does not own `/`. + if (concreteSegments[i] === '') { + continue; + } + const routeSegment = routeSegments[i]; + const isStaticSegment = routeSegment !== undefined && !routeSegment.startsWith('['); + if (!isStaticSegment) { + dynamicIndices.push(i); + } + } + if (dynamicIndices.length === 0 || dynamicIndices.length > MAX_DYNAMIC_SEGMENTS) { + return false; + } + // Enumerate the keep-literal/placeholder combinations as a bitmask over those + // positions (a set bit keeps the concrete value, an unset bit is a + // placeholder). The all-literal combination is skipped: a fully concrete path + // is a static route, already covered by the static filter and the early + // prefix check, so it can never appear in the dynamic filter as a pattern. + const allLiteral = (1 << dynamicIndices.length) - 1; + for(let mask = 0; mask < allLiteral; mask++){ + const segments = concreteSegments.slice(); + for(let bit = 0; bit < dynamicIndices.length; bit++){ + if ((mask & 1 << bit) === 0) { + segments[dynamicIndices[bit]] = DYNAMIC_FILTER_PLACEHOLDER; + } + } + if (test(segments.join('/'))) { + return true; + } + } + return false; +} + +//# sourceMappingURL=dynamic-filter-pattern.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c741f30fbf40282b38c5335f7dd1c42f97fd9d04 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/dynamic-filter-pattern.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/dynamic-filter-pattern.ts"],"sourcesContent":["// The client router filter handles app routes that begin with a dynamic segment\n// (e.g. `/[locale]/about`). Such routes have no static prefix to anchor the\n// prefix-based dynamic filter on, so the build-time producer\n// (`createClientRouterFilter`) stores them as a normalized pattern with dynamic\n// segments replaced by the placeholder token below, and the pages router\n// reconstructs matching candidates from the route it resolved a navigation to.\n\n/**\n * A token that can never collide with a real path segment (dynamic segments are\n * always `[name]`, `[...name]`, or `[[...name]]`, and static segments never\n * equal `[]`). Shared with the builder's `normalizeRouteToFilterPattern`.\n */\nexport const DYNAMIC_FILTER_PLACEHOLDER = '[]'\n\n/**\n * Beyond this many dynamic segments the 2^n candidate set is skipped. Real\n * routes never approach this; the cap only guards against pathological input.\n */\nconst MAX_DYNAMIC_SEGMENTS = 8\n\n/**\n * Test whether any app route that could shadow the resolved pages route passes\n * `test` (typically a dynamic-filter membership check). An app route can only\n * win over a matching pages route by turning some of that route's dynamic\n * positions into static segments, so we enumerate keeping each such position\n * either literal (static in the app route) or a placeholder (still dynamic in\n * the app route) and return as soon as one passes.\n *\n * A static route segment pins its position to that literal; every other\n * concrete position is dynamic and thus a candidate for a placeholder. That\n * includes the tail a trailing catch-all (`[...slug]`/`[[...slug]]`) absorbs,\n * which is why a catch-all route legitimately has fewer segments than the path\n * it matched.\n *\n * Order is irrelevant: any match means the path is shadowed, and resolution is\n * handed to the server via a hard navigation regardless of which candidate\n * matched.\n */\nexport function hasDynamicFilterCandidate(\n routePattern: string,\n concretePathname: string,\n test: (candidate: string) => boolean\n): boolean {\n const routeSegments = routePattern.split('/')\n const concreteSegments = concretePathname.split('/')\n\n const lastSegment = routeSegments[routeSegments.length - 1] ?? ''\n const hasCatchAll =\n lastSegment.startsWith('[...') || lastSegment.startsWith('[[...')\n\n // A non-catch-all route always has the same segment count as the path it\n // matched; a mismatch there means the inputs don't line up. A catch-all route\n // legitimately differs because its final param absorbs the remaining\n // segments.\n if (!hasCatchAll && routeSegments.length !== concreteSegments.length) {\n return false\n }\n\n // Collect the concrete positions that are dynamic in the matched route: any\n // position without a static route segment (a dynamic param, or one absorbed\n // by the trailing catch-all).\n const dynamicIndices: number[] = []\n for (let i = 1; i < concreteSegments.length; i++) {\n // An empty concrete segment is not a real path segment (splitting `/`\n // yields a trailing `''`). A trailing optional catch-all matches it by\n // absorbing nothing, so it must not be treated as a dynamic position:\n // otherwise `/` would reconstruct the `/[]` candidate and spuriously match\n // a root-level dynamic app route such as `/[lang]`, which does not own `/`.\n if (concreteSegments[i] === '') {\n continue\n }\n const routeSegment = routeSegments[i]\n const isStaticSegment =\n routeSegment !== undefined && !routeSegment.startsWith('[')\n if (!isStaticSegment) {\n dynamicIndices.push(i)\n }\n }\n\n if (\n dynamicIndices.length === 0 ||\n dynamicIndices.length > MAX_DYNAMIC_SEGMENTS\n ) {\n return false\n }\n\n // Enumerate the keep-literal/placeholder combinations as a bitmask over those\n // positions (a set bit keeps the concrete value, an unset bit is a\n // placeholder). The all-literal combination is skipped: a fully concrete path\n // is a static route, already covered by the static filter and the early\n // prefix check, so it can never appear in the dynamic filter as a pattern.\n const allLiteral = (1 << dynamicIndices.length) - 1\n for (let mask = 0; mask < allLiteral; mask++) {\n const segments = concreteSegments.slice()\n for (let bit = 0; bit < dynamicIndices.length; bit++) {\n if ((mask & (1 << bit)) === 0) {\n segments[dynamicIndices[bit]] = DYNAMIC_FILTER_PLACEHOLDER\n }\n }\n if (test(segments.join('/'))) {\n return true\n }\n }\n\n return false\n}\n"],"names":["DYNAMIC_FILTER_PLACEHOLDER","hasDynamicFilterCandidate","MAX_DYNAMIC_SEGMENTS","routePattern","concretePathname","test","routeSegments","split","concreteSegments","lastSegment","length","hasCatchAll","startsWith","dynamicIndices","i","routeSegment","isStaticSegment","undefined","push","allLiteral","mask","segments","slice","bit","join"],"mappings":"AAAA,gFAAgF;AAChF,4EAA4E;AAC5E,6DAA6D;AAC7D,gFAAgF;AAChF,yEAAyE;AACzE,+EAA+E;AAE/E;;;;CAIC;;;;;;;;;;;;;;;IACYA,0BAA0B;eAA1BA;;IA0BGC,yBAAyB;eAAzBA;;;AA1BT,MAAMD,6BAA6B;AAE1C;;;CAGC,GACD,MAAME,uBAAuB;AAoBtB,SAASD,0BACdE,YAAoB,EACpBC,gBAAwB,EACxBC,IAAoC;IAEpC,MAAMC,gBAAgBH,aAAaI,KAAK,CAAC;IACzC,MAAMC,mBAAmBJ,iBAAiBG,KAAK,CAAC;IAEhD,MAAME,cAAcH,aAAa,CAACA,cAAcI,MAAM,GAAG,EAAE,IAAI;IAC/D,MAAMC,cACJF,YAAYG,UAAU,CAAC,WAAWH,YAAYG,UAAU,CAAC;IAE3D,yEAAyE;IACzE,8EAA8E;IAC9E,qEAAqE;IACrE,YAAY;IACZ,IAAI,CAACD,eAAeL,cAAcI,MAAM,KAAKF,iBAAiBE,MAAM,EAAE;QACpE,OAAO;IACT;IAEA,4EAA4E;IAC5E,4EAA4E;IAC5E,8BAA8B;IAC9B,MAAMG,iBAA2B,EAAE;IACnC,IAAK,IAAIC,IAAI,GAAGA,IAAIN,iBAAiBE,MAAM,EAAEI,IAAK;QAChD,sEAAsE;QACtE,uEAAuE;QACvE,sEAAsE;QACtE,2EAA2E;QAC3E,4EAA4E;QAC5E,IAAIN,gBAAgB,CAACM,EAAE,KAAK,IAAI;YAC9B;QACF;QACA,MAAMC,eAAeT,aAAa,CAACQ,EAAE;QACrC,MAAME,kBACJD,iBAAiBE,aAAa,CAACF,aAAaH,UAAU,CAAC;QACzD,IAAI,CAACI,iBAAiB;YACpBH,eAAeK,IAAI,CAACJ;QACtB;IACF;IAEA,IACED,eAAeH,MAAM,KAAK,KAC1BG,eAAeH,MAAM,GAAGR,sBACxB;QACA,OAAO;IACT;IAEA,8EAA8E;IAC9E,mEAAmE;IACnE,8EAA8E;IAC9E,wEAAwE;IACxE,2EAA2E;IAC3E,MAAMiB,aAAa,AAAC,CAAA,KAAKN,eAAeH,MAAM,AAAD,IAAK;IAClD,IAAK,IAAIU,OAAO,GAAGA,OAAOD,YAAYC,OAAQ;QAC5C,MAAMC,WAAWb,iBAAiBc,KAAK;QACvC,IAAK,IAAIC,MAAM,GAAGA,MAAMV,eAAeH,MAAM,EAAEa,MAAO;YACpD,IAAI,AAACH,CAAAA,OAAQ,KAAKG,GAAG,MAAO,GAAG;gBAC7BF,QAAQ,CAACR,cAAc,CAACU,IAAI,CAAC,GAAGvB;YAClC;QACF;QACA,IAAIK,KAAKgB,SAASG,IAAI,CAAC,OAAO;YAC5B,OAAO;QACT;IACF;IAEA,OAAO;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..889297d10a0d859095a67451065400a601ad3222 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.d.ts @@ -0,0 +1 @@ +export default function escapePathDelimiters(segment: string, escapeEncoded?: boolean): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js new file mode 100644 index 0000000000000000000000000000000000000000..e5bacd9751ee4c48b8b11cd96914b4388c6fa2da --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js @@ -0,0 +1,16 @@ +// escape delimiters used by path-to-regexp +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return escapePathDelimiters; + } +}); +function escapePathDelimiters(segment, escapeEncoded) { + return segment.replace(new RegExp(`([/#?\\\\]${escapeEncoded ? '|%(2f|23|3f|5c)' : ''})`, 'gi'), (char)=>encodeURIComponent(char)); +} + +//# sourceMappingURL=escape-path-delimiters.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d09aaed9fc3b4f9eed1186c622fbd4f41e35be7a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/escape-path-delimiters.ts"],"sourcesContent":["// escape delimiters used by path-to-regexp\nexport default function escapePathDelimiters(\n segment: string,\n escapeEncoded?: boolean\n): string {\n return segment.replace(\n new RegExp(`([/#?\\\\\\\\]${escapeEncoded ? '|%(2f|23|3f|5c)' : ''})`, 'gi'),\n (char: string) => encodeURIComponent(char)\n )\n}\n"],"names":["escapePathDelimiters","segment","escapeEncoded","replace","RegExp","char","encodeURIComponent"],"mappings":"AAAA,2CAA2C;;;;;+BAC3C;;;eAAwBA;;;AAAT,SAASA,qBACtBC,OAAe,EACfC,aAAuB;IAEvB,OAAOD,QAAQE,OAAO,CACpB,IAAIC,OAAO,CAAC,UAAU,EAAEF,gBAAgB,oBAAoB,GAAG,CAAC,CAAC,EAAE,OACnE,CAACG,OAAiBC,mBAAmBD;AAEzC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..413780ad89ae079f4b77c3985272f91a02522386 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.d.ts @@ -0,0 +1,7 @@ +import type { NextPathnameInfo } from './get-next-pathname-info'; +interface ExtendedInfo extends NextPathnameInfo { + defaultLocale?: string; + ignorePrefix?: boolean; +} +export declare function formatNextPathnameInfo(info: ExtendedInfo): string; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js new file mode 100644 index 0000000000000000000000000000000000000000..b5cd1c940babee72b4835b3ddf772ef9f4e1e5fd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "formatNextPathnameInfo", { + enumerable: true, + get: function() { + return formatNextPathnameInfo; + } +}); +const _removetrailingslash = require("./remove-trailing-slash"); +const _addpathprefix = require("./add-path-prefix"); +const _addpathsuffix = require("./add-path-suffix"); +const _addlocale = require("./add-locale"); +function formatNextPathnameInfo(info) { + let pathname = (0, _addlocale.addLocale)(info.pathname, info.locale, info.buildId ? undefined : info.defaultLocale, info.ignorePrefix); + if (info.buildId || !info.trailingSlash) { + pathname = (0, _removetrailingslash.removeTrailingSlash)(pathname); + } + if (info.buildId) { + pathname = (0, _addpathsuffix.addPathSuffix)((0, _addpathprefix.addPathPrefix)(pathname, `/_next/data/${info.buildId}`), info.pathname === '/' ? 'index.json' : '.json'); + } + pathname = (0, _addpathprefix.addPathPrefix)(pathname, info.basePath); + return !info.buildId && info.trailingSlash ? !pathname.endsWith('/') ? (0, _addpathsuffix.addPathSuffix)(pathname, '/') : pathname : (0, _removetrailingslash.removeTrailingSlash)(pathname); +} + +//# sourceMappingURL=format-next-pathname-info.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js.map new file mode 100644 index 0000000000000000000000000000000000000000..15539d058acca2784b4678155105b98ebd324947 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/format-next-pathname-info.ts"],"sourcesContent":["import type { NextPathnameInfo } from './get-next-pathname-info'\nimport { removeTrailingSlash } from './remove-trailing-slash'\nimport { addPathPrefix } from './add-path-prefix'\nimport { addPathSuffix } from './add-path-suffix'\nimport { addLocale } from './add-locale'\n\ninterface ExtendedInfo extends NextPathnameInfo {\n defaultLocale?: string\n ignorePrefix?: boolean\n}\n\nexport function formatNextPathnameInfo(info: ExtendedInfo) {\n let pathname = addLocale(\n info.pathname,\n info.locale,\n info.buildId ? undefined : info.defaultLocale,\n info.ignorePrefix\n )\n\n if (info.buildId || !info.trailingSlash) {\n pathname = removeTrailingSlash(pathname)\n }\n\n if (info.buildId) {\n pathname = addPathSuffix(\n addPathPrefix(pathname, `/_next/data/${info.buildId}`),\n info.pathname === '/' ? 'index.json' : '.json'\n )\n }\n\n pathname = addPathPrefix(pathname, info.basePath)\n return !info.buildId && info.trailingSlash\n ? !pathname.endsWith('/')\n ? addPathSuffix(pathname, '/')\n : pathname\n : removeTrailingSlash(pathname)\n}\n"],"names":["formatNextPathnameInfo","info","pathname","addLocale","locale","buildId","undefined","defaultLocale","ignorePrefix","trailingSlash","removeTrailingSlash","addPathSuffix","addPathPrefix","basePath","endsWith"],"mappings":";;;;+BAWgBA;;;eAAAA;;;qCAVoB;+BACN;+BACA;2BACJ;AAOnB,SAASA,uBAAuBC,IAAkB;IACvD,IAAIC,WAAWC,IAAAA,oBAAS,EACtBF,KAAKC,QAAQ,EACbD,KAAKG,MAAM,EACXH,KAAKI,OAAO,GAAGC,YAAYL,KAAKM,aAAa,EAC7CN,KAAKO,YAAY;IAGnB,IAAIP,KAAKI,OAAO,IAAI,CAACJ,KAAKQ,aAAa,EAAE;QACvCP,WAAWQ,IAAAA,wCAAmB,EAACR;IACjC;IAEA,IAAID,KAAKI,OAAO,EAAE;QAChBH,WAAWS,IAAAA,4BAAa,EACtBC,IAAAA,4BAAa,EAACV,UAAU,CAAC,YAAY,EAAED,KAAKI,OAAO,EAAE,GACrDJ,KAAKC,QAAQ,KAAK,MAAM,eAAe;IAE3C;IAEAA,WAAWU,IAAAA,4BAAa,EAACV,UAAUD,KAAKY,QAAQ;IAChD,OAAO,CAACZ,KAAKI,OAAO,IAAIJ,KAAKQ,aAAa,GACtC,CAACP,SAASY,QAAQ,CAAC,OACjBH,IAAAA,4BAAa,EAACT,UAAU,OACxBA,WACFQ,IAAAA,wCAAmB,EAACR;AAC1B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c044a3d9dc05d167b0655968cd1cc0f53cbcf235 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.d.ts @@ -0,0 +1,4 @@ +import type { UrlObject } from 'url'; +export declare function formatUrl(urlObj: UrlObject): string; +export declare const urlObjectKeys: string[]; +export declare function formatWithValidation(url: UrlObject): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.js new file mode 100644 index 0000000000000000000000000000000000000000..820095f7f1225f4a0eea593dc637d66a98dc6854 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.js @@ -0,0 +1,111 @@ +// Format function modified from nodejs +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + formatUrl: null, + formatWithValidation: null, + urlObjectKeys: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + formatUrl: function() { + return formatUrl; + }, + formatWithValidation: function() { + return formatWithValidation; + }, + urlObjectKeys: function() { + return urlObjectKeys; + } +}); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _querystring = /*#__PURE__*/ _interop_require_wildcard._(require("./querystring")); +const slashedProtocols = /https?|ftp|gopher|file/; +function formatUrl(urlObj) { + let { auth, hostname } = urlObj; + let protocol = urlObj.protocol || ''; + let pathname = urlObj.pathname || ''; + let hash = urlObj.hash || ''; + let query = urlObj.query || ''; + let host = false; + auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''; + if (urlObj.host) { + host = auth + urlObj.host; + } else if (hostname) { + host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname); + if (urlObj.port) { + host += ':' + urlObj.port; + } + } + if (query && typeof query === 'object') { + query = String(_querystring.urlQueryToSearchParams(query)); + } + let search = urlObj.search || query && `?${query}` || ''; + if (protocol && !protocol.endsWith(':')) protocol += ':'; + if (urlObj.slashes || (!protocol || slashedProtocols.test(protocol)) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname[0] !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + if (hash && hash[0] !== '#') hash = '#' + hash; + if (search && search[0] !== '?') search = '?' + search; + pathname = pathname.replace(/[?#]/g, encodeURIComponent); + search = search.replace('#', '%23'); + return `${protocol}${host}${pathname}${search}${hash}`; +} +const urlObjectKeys = [ + 'auth', + 'hash', + 'host', + 'hostname', + 'href', + 'path', + 'pathname', + 'port', + 'protocol', + 'query', + 'search', + 'slashes' +]; +function formatWithValidation(url) { + if (process.env.NODE_ENV === 'development') { + if (url !== null && typeof url === 'object') { + Object.keys(url).forEach((key)=>{ + if (!urlObjectKeys.includes(key)) { + console.warn(`Unknown key passed via urlObject into url.format: ${key}`); + } + }); + } + } + return formatUrl(url); +} + +//# sourceMappingURL=format-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9f19e4cf7bc1498710d68d8aab24305c1c30a553 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/format-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/format-url.ts"],"sourcesContent":["// Format function modified from nodejs\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { UrlObject } from 'url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport * as querystring from './querystring'\n\nconst slashedProtocols = /https?|ftp|gopher|file/\n\nexport function formatUrl(urlObj: UrlObject) {\n let { auth, hostname } = urlObj\n let protocol = urlObj.protocol || ''\n let pathname = urlObj.pathname || ''\n let hash = urlObj.hash || ''\n let query = urlObj.query || ''\n let host: string | false = false\n\n auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''\n\n if (urlObj.host) {\n host = auth + urlObj.host\n } else if (hostname) {\n host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname)\n if (urlObj.port) {\n host += ':' + urlObj.port\n }\n }\n\n if (query && typeof query === 'object') {\n query = String(querystring.urlQueryToSearchParams(query as ParsedUrlQuery))\n }\n\n let search = urlObj.search || (query && `?${query}`) || ''\n\n if (protocol && !protocol.endsWith(':')) protocol += ':'\n\n if (\n urlObj.slashes ||\n ((!protocol || slashedProtocols.test(protocol)) && host !== false)\n ) {\n host = '//' + (host || '')\n if (pathname && pathname[0] !== '/') pathname = '/' + pathname\n } else if (!host) {\n host = ''\n }\n\n if (hash && hash[0] !== '#') hash = '#' + hash\n if (search && search[0] !== '?') search = '?' + search\n\n pathname = pathname.replace(/[?#]/g, encodeURIComponent)\n search = search.replace('#', '%23')\n\n return `${protocol}${host}${pathname}${search}${hash}`\n}\n\nexport const urlObjectKeys = [\n 'auth',\n 'hash',\n 'host',\n 'hostname',\n 'href',\n 'path',\n 'pathname',\n 'port',\n 'protocol',\n 'query',\n 'search',\n 'slashes',\n]\n\nexport function formatWithValidation(url: UrlObject): string {\n if (process.env.NODE_ENV === 'development') {\n if (url !== null && typeof url === 'object') {\n Object.keys(url).forEach((key) => {\n if (!urlObjectKeys.includes(key)) {\n console.warn(\n `Unknown key passed via urlObject into url.format: ${key}`\n )\n }\n })\n }\n }\n\n return formatUrl(url)\n}\n"],"names":["formatUrl","formatWithValidation","urlObjectKeys","slashedProtocols","urlObj","auth","hostname","protocol","pathname","hash","query","host","encodeURIComponent","replace","indexOf","port","String","querystring","urlQueryToSearchParams","search","endsWith","slashes","test","url","process","env","NODE_ENV","Object","keys","forEach","key","includes","console","warn"],"mappings":"AAAA,uCAAuC;AACvC,sDAAsD;AACtD,EAAE;AACF,0EAA0E;AAC1E,gEAAgE;AAChE,sEAAsE;AACtE,sEAAsE;AACtE,4EAA4E;AAC5E,qEAAqE;AACrE,wBAAwB;AACxB,EAAE;AACF,0EAA0E;AAC1E,yDAAyD;AACzD,EAAE;AACF,0EAA0E;AAC1E,6DAA6D;AAC7D,4EAA4E;AAC5E,2EAA2E;AAC3E,wEAAwE;AACxE,4EAA4E;AAC5E,yCAAyC;;;;;;;;;;;;;;;;;IAQzBA,SAAS;eAATA;;IA6DAC,oBAAoB;eAApBA;;IAfHC,aAAa;eAAbA;;;;uEAlDgB;AAE7B,MAAMC,mBAAmB;AAElB,SAASH,UAAUI,MAAiB;IACzC,IAAI,EAAEC,IAAI,EAAEC,QAAQ,EAAE,GAAGF;IACzB,IAAIG,WAAWH,OAAOG,QAAQ,IAAI;IAClC,IAAIC,WAAWJ,OAAOI,QAAQ,IAAI;IAClC,IAAIC,OAAOL,OAAOK,IAAI,IAAI;IAC1B,IAAIC,QAAQN,OAAOM,KAAK,IAAI;IAC5B,IAAIC,OAAuB;IAE3BN,OAAOA,OAAOO,mBAAmBP,MAAMQ,OAAO,CAAC,QAAQ,OAAO,MAAM;IAEpE,IAAIT,OAAOO,IAAI,EAAE;QACfA,OAAON,OAAOD,OAAOO,IAAI;IAC3B,OAAO,IAAIL,UAAU;QACnBK,OAAON,OAAQ,CAAA,CAACC,SAASQ,OAAO,CAAC,OAAO,CAAC,CAAC,EAAER,SAAS,CAAC,CAAC,GAAGA,QAAO;QACjE,IAAIF,OAAOW,IAAI,EAAE;YACfJ,QAAQ,MAAMP,OAAOW,IAAI;QAC3B;IACF;IAEA,IAAIL,SAAS,OAAOA,UAAU,UAAU;QACtCA,QAAQM,OAAOC,aAAYC,sBAAsB,CAACR;IACpD;IAEA,IAAIS,SAASf,OAAOe,MAAM,IAAKT,SAAS,CAAC,CAAC,EAAEA,OAAO,IAAK;IAExD,IAAIH,YAAY,CAACA,SAASa,QAAQ,CAAC,MAAMb,YAAY;IAErD,IACEH,OAAOiB,OAAO,IACb,AAAC,CAAA,CAACd,YAAYJ,iBAAiBmB,IAAI,CAACf,SAAQ,KAAMI,SAAS,OAC5D;QACAA,OAAO,OAAQA,CAAAA,QAAQ,EAAC;QACxB,IAAIH,YAAYA,QAAQ,CAAC,EAAE,KAAK,KAAKA,WAAW,MAAMA;IACxD,OAAO,IAAI,CAACG,MAAM;QAChBA,OAAO;IACT;IAEA,IAAIF,QAAQA,IAAI,CAAC,EAAE,KAAK,KAAKA,OAAO,MAAMA;IAC1C,IAAIU,UAAUA,MAAM,CAAC,EAAE,KAAK,KAAKA,SAAS,MAAMA;IAEhDX,WAAWA,SAASK,OAAO,CAAC,SAASD;IACrCO,SAASA,OAAON,OAAO,CAAC,KAAK;IAE7B,OAAO,GAAGN,WAAWI,OAAOH,WAAWW,SAASV,MAAM;AACxD;AAEO,MAAMP,gBAAgB;IAC3B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAEM,SAASD,qBAAqBsB,GAAc;IACjD,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1C,IAAIH,QAAQ,QAAQ,OAAOA,QAAQ,UAAU;YAC3CI,OAAOC,IAAI,CAACL,KAAKM,OAAO,CAAC,CAACC;gBACxB,IAAI,CAAC5B,cAAc6B,QAAQ,CAACD,MAAM;oBAChCE,QAAQC,IAAI,CACV,CAAC,kDAAkD,EAAEH,KAAK;gBAE9D;YACF;QACF;IACF;IAEA,OAAO9B,UAAUuB;AACnB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d35319d3c9290afb1dbcc8b4baafe2f953c3604 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.d.ts @@ -0,0 +1 @@ +export default function getAssetPathFromRoute(route: string, ext?: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js new file mode 100644 index 0000000000000000000000000000000000000000..922779080cfdf06dfee6a79495e8f95e5936cdf8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js @@ -0,0 +1,18 @@ +// Translates a logical route into its pages asset path (relative from a common prefix) +// "asset path" being its javascript file, data file, prerendered html,... +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return getAssetPathFromRoute; + } +}); +function getAssetPathFromRoute(route, ext = '') { + const path = route === '/' ? '/index' : /^\/index(\/|$)/.test(route) ? `/index${route}` : route; + return path + ext; +} + +//# sourceMappingURL=get-asset-path-from-route.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js.map new file mode 100644 index 0000000000000000000000000000000000000000..92bfb9bbee54555f4fa83d4da6c01a0a53d3cfc9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/get-asset-path-from-route.ts"],"sourcesContent":["// Translates a logical route into its pages asset path (relative from a common prefix)\n// \"asset path\" being its javascript file, data file, prerendered html,...\nexport default function getAssetPathFromRoute(\n route: string,\n ext: string = ''\n): string {\n const path =\n route === '/'\n ? '/index'\n : /^\\/index(\\/|$)/.test(route)\n ? `/index${route}`\n : route\n return path + ext\n}\n"],"names":["getAssetPathFromRoute","route","ext","path","test"],"mappings":"AAAA,uFAAuF;AACvF,0EAA0E;;;;;+BAC1E;;;eAAwBA;;;AAAT,SAASA,sBACtBC,KAAa,EACbC,MAAc,EAAE;IAEhB,MAAMC,OACJF,UAAU,MACN,WACA,iBAAiBG,IAAI,CAACH,SACpB,CAAC,MAAM,EAAEA,OAAO,GAChBA;IACR,OAAOE,OAAOD;AAChB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b130c2e5666409426c22caef38409e45214d367a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.d.ts @@ -0,0 +1,61 @@ +import type { DynamicParam } from '../../../../server/app-render/app-render'; +import type { LoaderTree } from '../../../../server/lib/app-dir-module'; +import type { OpaqueFallbackRouteParams } from '../../../../server/request/fallback-params'; +import type { Params } from '../../../../server/request/params'; +import type { DynamicParamTypesShort } from '../../app-router-types'; +export declare function interpolateParallelRouteParams(loaderTree: LoaderTree, params: Params, pagePath: string, fallbackRouteParams: OpaqueFallbackRouteParams | null): Params; +/** + * + * Shared logic on client and server for creating a dynamic param value. + * + * This code needs to be shared with the client so it can extract dynamic route + * params from the URL without a server request. + * + * Because everything in this module is sent to the client, we should aim to + * keep this code as simple as possible. The special case handling for catchall + * and optional is, alas, unfortunate. + */ +export declare function getDynamicParam(interpolatedParams: Params, segmentKey: string, dynamicParamType: DynamicParamTypesShort, fallbackRouteParams: OpaqueFallbackRouteParams | null, staticSiblings: readonly string[] | null): DynamicParam; +/** + * Regular expression pattern used to match route parameters. + * Matches both single parameters and parameter groups. + * Examples: + * - `[[...slug]]` matches parameter group with key 'slug', repeat: true, optional: true + * - `[...slug]` matches parameter group with key 'slug', repeat: true, optional: false + * - `[[foo]]` matches parameter with key 'foo', repeat: false, optional: true + * - `[bar]` matches parameter with key 'bar', repeat: false, optional: false + */ +export declare const PARAMETER_PATTERN: RegExp; +/** + * Parses a given parameter from a route to a data structure that can be used + * to generate the parametrized route. + * Examples: + * - `[[...slug]]` -> `{ key: 'slug', repeat: true, optional: true }` + * - `[...slug]` -> `{ key: 'slug', repeat: true, optional: false }` + * - `[[foo]]` -> `{ key: 'foo', repeat: false, optional: true }` + * - `[bar]` -> `{ key: 'bar', repeat: false, optional: false }` + * - `fizz` -> `{ key: 'fizz', repeat: false, optional: false }` + * @param param - The parameter to parse. + * @returns The parsed parameter as a data structure. + */ +export declare function parseParameter(param: string): { + key: string; + repeat: boolean; + optional: boolean; +}; +/** + * Parses a matched parameter from the PARAMETER_PATTERN regex to a data structure that can be used + * to generate the parametrized route. + * Examples: + * - `[...slug]` -> `{ key: 'slug', repeat: true, optional: true }` + * - `...slug` -> `{ key: 'slug', repeat: true, optional: false }` + * - `[foo]` -> `{ key: 'foo', repeat: false, optional: true }` + * - `bar` -> `{ key: 'bar', repeat: false, optional: false }` + * @param param - The matched parameter to parse. + * @returns The parsed parameter as a data structure. + */ +export declare function parseMatchedParameter(param: string): { + key: string; + repeat: boolean; + optional: boolean; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.js new file mode 100644 index 0000000000000000000000000000000000000000..1771513824b7dd14c54507c0f7403e7a73d6d51b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.js @@ -0,0 +1,166 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + PARAMETER_PATTERN: null, + getDynamicParam: null, + interpolateParallelRouteParams: null, + parseMatchedParameter: null, + parseParameter: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + PARAMETER_PATTERN: function() { + return PARAMETER_PATTERN; + }, + getDynamicParam: function() { + return getDynamicParam; + }, + interpolateParallelRouteParams: function() { + return interpolateParallelRouteParams; + }, + parseMatchedParameter: function() { + return parseMatchedParameter; + }, + parseParameter: function() { + return parseParameter; + } +}); +const _invarianterror = require("../../invariant-error"); +const _parseloadertree = require("./parse-loader-tree"); +const _app = require("../routes/app"); +const _resolveparamvalue = require("./resolve-param-value"); +/** + * Gets the value of a param from the params object. This correctly handles the + * case where the param is a fallback route param and encodes the resulting + * value. + * + * @param interpolatedParams - The params object. + * @param segmentKey - The key of the segment. + * @param fallbackRouteParams - The fallback route params. + * @returns The value of the param. + */ function getParamValue(interpolatedParams, segmentKey, fallbackRouteParams) { + let value = interpolatedParams[segmentKey]; + if (fallbackRouteParams?.has(segmentKey)) { + // We know that the fallback route params has the segment key because we + // checked that above. + const placeholder = fallbackRouteParams.get(segmentKey); + value = placeholder; + } else if (Array.isArray(value)) { + value = value.map((i)=>encodeURIComponent(i)); + } else if (typeof value === 'string') { + value = encodeURIComponent(value); + } + return value; +} +function interpolateParallelRouteParams(loaderTree, params, pagePath, fallbackRouteParams) { + const interpolated = structuredClone(params); + // Stack-based traversal with depth tracking + const stack = [ + { + tree: loaderTree, + depth: 0 + } + ]; + // Parse the route from the provided page path. + const route = (0, _app.parseNormalizedAppRoute)(pagePath); + while(stack.length > 0){ + const { tree, depth } = stack.pop(); + const { segment, parallelRoutes } = (0, _parseloadertree.parseLoaderTree)(tree); + const appSegment = (0, _app.parseAppRouteSegment)(segment); + if (appSegment?.type === 'dynamic' && !interpolated.hasOwnProperty(appSegment.param.paramName) && // If the param is in the fallback route params, we don't need to + // interpolate it because it's already marked as being unknown. + !fallbackRouteParams?.has(appSegment.param.paramName)) { + const { paramName, paramType } = appSegment.param; + const paramValue = (0, _resolveparamvalue.resolveParamValue)(paramName, paramType, depth, route, interpolated); + if (paramValue !== undefined) { + interpolated[paramName] = paramValue; + } else if (paramType !== 'optional-catchall') { + throw new _invarianterror.InvariantError(`Could not resolve param value for segment: ${paramName}`); + } + } + // Calculate next depth - increment if this is not a route group and not empty + let nextDepth = depth; + if (appSegment && appSegment.type !== 'route-group' && appSegment.type !== 'parallel-route') { + nextDepth++; + } + // Add all parallel routes to the stack for processing + for (const parallelRoute of Object.values(parallelRoutes)){ + stack.push({ + tree: parallelRoute, + depth: nextDepth + }); + } + } + return interpolated; +} +function getDynamicParam(interpolatedParams, segmentKey, dynamicParamType, fallbackRouteParams, staticSiblings) { + let value = getParamValue(interpolatedParams, segmentKey, fallbackRouteParams); + // handle the case where an optional catchall does not have a value, + // e.g. `/dashboard/[[...slug]]` when requesting `/dashboard` + if (!value || value.length === 0) { + if (dynamicParamType === 'oc') { + return { + param: segmentKey, + value: null, + type: dynamicParamType, + treeSegment: [ + segmentKey, + '', + dynamicParamType, + staticSiblings + ] + }; + } + throw new _invarianterror.InvariantError(`Missing value for segment key: "${segmentKey}" with dynamic param type: ${dynamicParamType}`); + } + const paramCacheKey = Array.isArray(value) ? value.join('/') : value; + return { + param: segmentKey, + // The value that is passed to user code. + value, + // The value that is rendered in the router tree. + // TODO: If the number of static siblings exceeds some threshold (e.g., + // dozens or hundreds), consider sending a Bloom filter instead of the full + // array to reduce payload size. The client would then use the Bloom filter + // to check membership with a small false positive rate. + treeSegment: [ + segmentKey, + paramCacheKey, + dynamicParamType, + staticSiblings + ], + type: dynamicParamType + }; +} +const PARAMETER_PATTERN = /^([^[]*)\[((?:\[[^\]]*\])|[^\]]+)\](.*)$/; +function parseParameter(param) { + const match = param.match(PARAMETER_PATTERN); + if (!match) { + return parseMatchedParameter(param); + } + return parseMatchedParameter(match[2]); +} +function parseMatchedParameter(param) { + const optional = param.startsWith('[') && param.endsWith(']'); + if (optional) { + param = param.slice(1, -1); + } + const repeat = param.startsWith('...'); + if (repeat) { + param = param.slice(3); + } + return { + key: param, + repeat, + optional + }; +} + +//# sourceMappingURL=get-dynamic-param.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.js.map new file mode 100644 index 0000000000000000000000000000000000000000..73c837fa2e72da9e3d3c76f9971f6379f1a20c53 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-dynamic-param.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/get-dynamic-param.ts"],"sourcesContent":["import type { DynamicParam } from '../../../../server/app-render/app-render'\nimport type { LoaderTree } from '../../../../server/lib/app-dir-module'\nimport type { OpaqueFallbackRouteParams } from '../../../../server/request/fallback-params'\nimport type { Params } from '../../../../server/request/params'\nimport type { DynamicParamTypesShort } from '../../app-router-types'\nimport { InvariantError } from '../../invariant-error'\nimport { parseLoaderTree } from './parse-loader-tree'\nimport { parseNormalizedAppRoute, parseAppRouteSegment } from '../routes/app'\nimport { resolveParamValue } from './resolve-param-value'\n\n/**\n * Gets the value of a param from the params object. This correctly handles the\n * case where the param is a fallback route param and encodes the resulting\n * value.\n *\n * @param interpolatedParams - The params object.\n * @param segmentKey - The key of the segment.\n * @param fallbackRouteParams - The fallback route params.\n * @returns The value of the param.\n */\nfunction getParamValue(\n interpolatedParams: Params,\n segmentKey: string,\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n) {\n let value = interpolatedParams[segmentKey]\n\n if (fallbackRouteParams?.has(segmentKey)) {\n // We know that the fallback route params has the segment key because we\n // checked that above.\n const placeholder = fallbackRouteParams.get(segmentKey)!\n value = placeholder\n } else if (Array.isArray(value)) {\n value = value.map((i) => encodeURIComponent(i))\n } else if (typeof value === 'string') {\n value = encodeURIComponent(value)\n }\n\n return value\n}\n\nexport function interpolateParallelRouteParams(\n loaderTree: LoaderTree,\n params: Params,\n pagePath: string,\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n): Params {\n const interpolated = structuredClone(params)\n\n // Stack-based traversal with depth tracking\n const stack: Array<{ tree: LoaderTree; depth: number }> = [\n { tree: loaderTree, depth: 0 },\n ]\n\n // Parse the route from the provided page path.\n const route = parseNormalizedAppRoute(pagePath)\n\n while (stack.length > 0) {\n const { tree, depth } = stack.pop()!\n const { segment, parallelRoutes } = parseLoaderTree(tree)\n\n const appSegment = parseAppRouteSegment(segment)\n\n if (\n appSegment?.type === 'dynamic' &&\n !interpolated.hasOwnProperty(appSegment.param.paramName) &&\n // If the param is in the fallback route params, we don't need to\n // interpolate it because it's already marked as being unknown.\n !fallbackRouteParams?.has(appSegment.param.paramName)\n ) {\n const { paramName, paramType } = appSegment.param\n\n const paramValue = resolveParamValue(\n paramName,\n paramType,\n depth,\n route,\n interpolated\n )\n\n if (paramValue !== undefined) {\n interpolated[paramName] = paramValue\n } else if (paramType !== 'optional-catchall') {\n throw new InvariantError(\n `Could not resolve param value for segment: ${paramName}`\n )\n }\n }\n\n // Calculate next depth - increment if this is not a route group and not empty\n let nextDepth = depth\n if (\n appSegment &&\n appSegment.type !== 'route-group' &&\n appSegment.type !== 'parallel-route'\n ) {\n nextDepth++\n }\n\n // Add all parallel routes to the stack for processing\n for (const parallelRoute of Object.values(parallelRoutes)) {\n stack.push({ tree: parallelRoute, depth: nextDepth })\n }\n }\n\n return interpolated\n}\n\n/**\n *\n * Shared logic on client and server for creating a dynamic param value.\n *\n * This code needs to be shared with the client so it can extract dynamic route\n * params from the URL without a server request.\n *\n * Because everything in this module is sent to the client, we should aim to\n * keep this code as simple as possible. The special case handling for catchall\n * and optional is, alas, unfortunate.\n */\nexport function getDynamicParam(\n interpolatedParams: Params,\n segmentKey: string,\n dynamicParamType: DynamicParamTypesShort,\n fallbackRouteParams: OpaqueFallbackRouteParams | null,\n staticSiblings: readonly string[] | null\n): DynamicParam {\n let value: string | string[] | undefined = getParamValue(\n interpolatedParams,\n segmentKey,\n fallbackRouteParams\n )\n\n // handle the case where an optional catchall does not have a value,\n // e.g. `/dashboard/[[...slug]]` when requesting `/dashboard`\n if (!value || value.length === 0) {\n if (dynamicParamType === 'oc') {\n return {\n param: segmentKey,\n value: null,\n type: dynamicParamType,\n treeSegment: [segmentKey, '', dynamicParamType, staticSiblings],\n }\n }\n\n throw new InvariantError(\n `Missing value for segment key: \"${segmentKey}\" with dynamic param type: ${dynamicParamType}`\n )\n }\n\n const paramCacheKey = Array.isArray(value) ? value.join('/') : value\n\n return {\n param: segmentKey,\n // The value that is passed to user code.\n value,\n // The value that is rendered in the router tree.\n // TODO: If the number of static siblings exceeds some threshold (e.g.,\n // dozens or hundreds), consider sending a Bloom filter instead of the full\n // array to reduce payload size. The client would then use the Bloom filter\n // to check membership with a small false positive rate.\n treeSegment: [segmentKey, paramCacheKey, dynamicParamType, staticSiblings],\n type: dynamicParamType,\n }\n}\n\n/**\n * Regular expression pattern used to match route parameters.\n * Matches both single parameters and parameter groups.\n * Examples:\n * - `[[...slug]]` matches parameter group with key 'slug', repeat: true, optional: true\n * - `[...slug]` matches parameter group with key 'slug', repeat: true, optional: false\n * - `[[foo]]` matches parameter with key 'foo', repeat: false, optional: true\n * - `[bar]` matches parameter with key 'bar', repeat: false, optional: false\n */\nexport const PARAMETER_PATTERN = /^([^[]*)\\[((?:\\[[^\\]]*\\])|[^\\]]+)\\](.*)$/\n\n/**\n * Parses a given parameter from a route to a data structure that can be used\n * to generate the parametrized route.\n * Examples:\n * - `[[...slug]]` -> `{ key: 'slug', repeat: true, optional: true }`\n * - `[...slug]` -> `{ key: 'slug', repeat: true, optional: false }`\n * - `[[foo]]` -> `{ key: 'foo', repeat: false, optional: true }`\n * - `[bar]` -> `{ key: 'bar', repeat: false, optional: false }`\n * - `fizz` -> `{ key: 'fizz', repeat: false, optional: false }`\n * @param param - The parameter to parse.\n * @returns The parsed parameter as a data structure.\n */\nexport function parseParameter(param: string) {\n const match = param.match(PARAMETER_PATTERN)\n\n if (!match) {\n return parseMatchedParameter(param)\n }\n\n return parseMatchedParameter(match[2])\n}\n\n/**\n * Parses a matched parameter from the PARAMETER_PATTERN regex to a data structure that can be used\n * to generate the parametrized route.\n * Examples:\n * - `[...slug]` -> `{ key: 'slug', repeat: true, optional: true }`\n * - `...slug` -> `{ key: 'slug', repeat: true, optional: false }`\n * - `[foo]` -> `{ key: 'foo', repeat: false, optional: true }`\n * - `bar` -> `{ key: 'bar', repeat: false, optional: false }`\n * @param param - The matched parameter to parse.\n * @returns The parsed parameter as a data structure.\n */\nexport function parseMatchedParameter(param: string) {\n const optional = param.startsWith('[') && param.endsWith(']')\n if (optional) {\n param = param.slice(1, -1)\n }\n const repeat = param.startsWith('...')\n if (repeat) {\n param = param.slice(3)\n }\n return { key: param, repeat, optional }\n}\n"],"names":["PARAMETER_PATTERN","getDynamicParam","interpolateParallelRouteParams","parseMatchedParameter","parseParameter","getParamValue","interpolatedParams","segmentKey","fallbackRouteParams","value","has","placeholder","get","Array","isArray","map","i","encodeURIComponent","loaderTree","params","pagePath","interpolated","structuredClone","stack","tree","depth","route","parseNormalizedAppRoute","length","pop","segment","parallelRoutes","parseLoaderTree","appSegment","parseAppRouteSegment","type","hasOwnProperty","param","paramName","paramType","paramValue","resolveParamValue","undefined","InvariantError","nextDepth","parallelRoute","Object","values","push","dynamicParamType","staticSiblings","treeSegment","paramCacheKey","join","match","optional","startsWith","endsWith","slice","repeat","key"],"mappings":";;;;;;;;;;;;;;;;;;IA8KaA,iBAAiB;eAAjBA;;IAvDGC,eAAe;eAAfA;;IA9EAC,8BAA8B;eAA9BA;;IAwKAC,qBAAqB;eAArBA;;IArBAC,cAAc;eAAdA;;;gCAvLe;iCACC;qBAC8B;mCAC5B;AAElC;;;;;;;;;CASC,GACD,SAASC,cACPC,kBAA0B,EAC1BC,UAAkB,EAClBC,mBAAqD;IAErD,IAAIC,QAAQH,kBAAkB,CAACC,WAAW;IAE1C,IAAIC,qBAAqBE,IAAIH,aAAa;QACxC,wEAAwE;QACxE,sBAAsB;QACtB,MAAMI,cAAcH,oBAAoBI,GAAG,CAACL;QAC5CE,QAAQE;IACV,OAAO,IAAIE,MAAMC,OAAO,CAACL,QAAQ;QAC/BA,QAAQA,MAAMM,GAAG,CAAC,CAACC,IAAMC,mBAAmBD;IAC9C,OAAO,IAAI,OAAOP,UAAU,UAAU;QACpCA,QAAQQ,mBAAmBR;IAC7B;IAEA,OAAOA;AACT;AAEO,SAASP,+BACdgB,UAAsB,EACtBC,MAAc,EACdC,QAAgB,EAChBZ,mBAAqD;IAErD,MAAMa,eAAeC,gBAAgBH;IAErC,4CAA4C;IAC5C,MAAMI,QAAoD;QACxD;YAAEC,MAAMN;YAAYO,OAAO;QAAE;KAC9B;IAED,+CAA+C;IAC/C,MAAMC,QAAQC,IAAAA,4BAAuB,EAACP;IAEtC,MAAOG,MAAMK,MAAM,GAAG,EAAG;QACvB,MAAM,EAAEJ,IAAI,EAAEC,KAAK,EAAE,GAAGF,MAAMM,GAAG;QACjC,MAAM,EAAEC,OAAO,EAAEC,cAAc,EAAE,GAAGC,IAAAA,gCAAe,EAACR;QAEpD,MAAMS,aAAaC,IAAAA,yBAAoB,EAACJ;QAExC,IACEG,YAAYE,SAAS,aACrB,CAACd,aAAae,cAAc,CAACH,WAAWI,KAAK,CAACC,SAAS,KACvD,iEAAiE;QACjE,+DAA+D;QAC/D,CAAC9B,qBAAqBE,IAAIuB,WAAWI,KAAK,CAACC,SAAS,GACpD;YACA,MAAM,EAAEA,SAAS,EAAEC,SAAS,EAAE,GAAGN,WAAWI,KAAK;YAEjD,MAAMG,aAAaC,IAAAA,oCAAiB,EAClCH,WACAC,WACAd,OACAC,OACAL;YAGF,IAAImB,eAAeE,WAAW;gBAC5BrB,YAAY,CAACiB,UAAU,GAAGE;YAC5B,OAAO,IAAID,cAAc,qBAAqB;gBAC5C,MAAM,IAAII,8BAAc,CACtB,CAAC,2CAA2C,EAAEL,WAAW;YAE7D;QACF;QAEA,8EAA8E;QAC9E,IAAIM,YAAYnB;QAChB,IACEQ,cACAA,WAAWE,IAAI,KAAK,iBACpBF,WAAWE,IAAI,KAAK,kBACpB;YACAS;QACF;QAEA,sDAAsD;QACtD,KAAK,MAAMC,iBAAiBC,OAAOC,MAAM,CAAChB,gBAAiB;YACzDR,MAAMyB,IAAI,CAAC;gBAAExB,MAAMqB;gBAAepB,OAAOmB;YAAU;QACrD;IACF;IAEA,OAAOvB;AACT;AAaO,SAASpB,gBACdK,kBAA0B,EAC1BC,UAAkB,EAClB0C,gBAAwC,EACxCzC,mBAAqD,EACrD0C,cAAwC;IAExC,IAAIzC,QAAuCJ,cACzCC,oBACAC,YACAC;IAGF,oEAAoE;IACpE,6DAA6D;IAC7D,IAAI,CAACC,SAASA,MAAMmB,MAAM,KAAK,GAAG;QAChC,IAAIqB,qBAAqB,MAAM;YAC7B,OAAO;gBACLZ,OAAO9B;gBACPE,OAAO;gBACP0B,MAAMc;gBACNE,aAAa;oBAAC5C;oBAAY;oBAAI0C;oBAAkBC;iBAAe;YACjE;QACF;QAEA,MAAM,IAAIP,8BAAc,CACtB,CAAC,gCAAgC,EAAEpC,WAAW,2BAA2B,EAAE0C,kBAAkB;IAEjG;IAEA,MAAMG,gBAAgBvC,MAAMC,OAAO,CAACL,SAASA,MAAM4C,IAAI,CAAC,OAAO5C;IAE/D,OAAO;QACL4B,OAAO9B;QACP,yCAAyC;QACzCE;QACA,iDAAiD;QACjD,uEAAuE;QACvE,2EAA2E;QAC3E,2EAA2E;QAC3E,wDAAwD;QACxD0C,aAAa;YAAC5C;YAAY6C;YAAeH;YAAkBC;SAAe;QAC1Ef,MAAMc;IACR;AACF;AAWO,MAAMjD,oBAAoB;AAc1B,SAASI,eAAeiC,KAAa;IAC1C,MAAMiB,QAAQjB,MAAMiB,KAAK,CAACtD;IAE1B,IAAI,CAACsD,OAAO;QACV,OAAOnD,sBAAsBkC;IAC/B;IAEA,OAAOlC,sBAAsBmD,KAAK,CAAC,EAAE;AACvC;AAaO,SAASnD,sBAAsBkC,KAAa;IACjD,MAAMkB,WAAWlB,MAAMmB,UAAU,CAAC,QAAQnB,MAAMoB,QAAQ,CAAC;IACzD,IAAIF,UAAU;QACZlB,QAAQA,MAAMqB,KAAK,CAAC,GAAG,CAAC;IAC1B;IACA,MAAMC,SAAStB,MAAMmB,UAAU,CAAC;IAChC,IAAIG,QAAQ;QACVtB,QAAQA,MAAMqB,KAAK,CAAC;IACtB;IACA,OAAO;QAAEE,KAAKvB;QAAOsB;QAAQJ;IAAS;AACxC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d3d101fe2bc3f60ddc38c6f0adadd7f2c830eba --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.d.ts @@ -0,0 +1,49 @@ +import type { I18NProvider } from '../../../../server/lib/i18n-provider'; +export interface NextPathnameInfo { + /** + * The base path in case the pathname included it. + */ + basePath?: string; + /** + * The buildId for when the parsed URL is a data URL. Parsing it can be + * disabled with the `parseData` option. + */ + buildId?: string; + /** + * If there was a locale in the pathname, this will hold its value. + */ + locale?: string; + /** + * The processed pathname without a base path, locale, or data URL elements + * when parsing it is enabled. + */ + pathname: string; + /** + * A boolean telling if the pathname had a trailingSlash. This can be only + * true if trailingSlash is enabled. + */ + trailingSlash?: boolean; +} +interface Options { + /** + * When passed to true, this function will also parse Nextjs data URLs. + */ + parseData?: boolean; + /** + * A partial of the Next.js configuration to parse the URL. + */ + nextConfig?: { + basePath?: string; + i18n?: { + locales?: readonly string[]; + } | null; + trailingSlash?: boolean; + }; + /** + * If provided, this normalizer will be used to detect the locale instead of + * the default locale detection. + */ + i18nProvider?: I18NProvider; +} +export declare function getNextPathnameInfo(pathname: string, options: Options): NextPathnameInfo; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js new file mode 100644 index 0000000000000000000000000000000000000000..fb0d7e4ea3c2188cfdf6ff679b82c21333d6536b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getNextPathnameInfo", { + enumerable: true, + get: function() { + return getNextPathnameInfo; + } +}); +const _normalizelocalepath = require("../../i18n/normalize-locale-path"); +const _removepathprefix = require("./remove-path-prefix"); +const _pathhasprefix = require("./path-has-prefix"); +function getNextPathnameInfo(pathname, options) { + const { basePath, i18n, trailingSlash } = options.nextConfig ?? {}; + const info = { + pathname, + trailingSlash: pathname !== '/' ? pathname.endsWith('/') : trailingSlash + }; + if (basePath && (0, _pathhasprefix.pathHasPrefix)(info.pathname, basePath)) { + info.pathname = (0, _removepathprefix.removePathPrefix)(info.pathname, basePath); + info.basePath = basePath; + } + let pathnameNoDataPrefix = info.pathname; + if (info.pathname.startsWith('/_next/data/') && info.pathname.endsWith('.json')) { + const paths = info.pathname.replace(/^\/_next\/data\//, '').replace(/\.json$/, '').split('/'); + const buildId = paths[0]; + info.buildId = buildId; + pathnameNoDataPrefix = paths[1] !== 'index' ? `/${paths.slice(1).join('/')}` : '/'; + // update pathname with normalized if enabled although + // we use normalized to populate locale info still + if (options.parseData === true) { + info.pathname = pathnameNoDataPrefix; + } + } + // If provided, use the locale route normalizer to detect the locale instead + // of the function below. + if (i18n) { + let result = options.i18nProvider ? options.i18nProvider.analyze(info.pathname) : (0, _normalizelocalepath.normalizeLocalePath)(info.pathname, i18n.locales); + info.locale = result.detectedLocale; + info.pathname = result.pathname ?? info.pathname; + if (!result.detectedLocale && info.buildId) { + result = options.i18nProvider ? options.i18nProvider.analyze(pathnameNoDataPrefix) : (0, _normalizelocalepath.normalizeLocalePath)(pathnameNoDataPrefix, i18n.locales); + if (result.detectedLocale) { + info.locale = result.detectedLocale; + } + } + } + return info; +} + +//# sourceMappingURL=get-next-pathname-info.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js.map new file mode 100644 index 0000000000000000000000000000000000000000..05b1a0db6aefec825f8d4013c3301d8ab84d758a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/get-next-pathname-info.ts"],"sourcesContent":["import { normalizeLocalePath } from '../../i18n/normalize-locale-path'\nimport { removePathPrefix } from './remove-path-prefix'\nimport { pathHasPrefix } from './path-has-prefix'\nimport type { I18NProvider } from '../../../../server/lib/i18n-provider'\n\nexport interface NextPathnameInfo {\n /**\n * The base path in case the pathname included it.\n */\n basePath?: string\n /**\n * The buildId for when the parsed URL is a data URL. Parsing it can be\n * disabled with the `parseData` option.\n */\n buildId?: string\n /**\n * If there was a locale in the pathname, this will hold its value.\n */\n locale?: string\n /**\n * The processed pathname without a base path, locale, or data URL elements\n * when parsing it is enabled.\n */\n pathname: string\n /**\n * A boolean telling if the pathname had a trailingSlash. This can be only\n * true if trailingSlash is enabled.\n */\n trailingSlash?: boolean\n}\n\ninterface Options {\n /**\n * When passed to true, this function will also parse Nextjs data URLs.\n */\n parseData?: boolean\n /**\n * A partial of the Next.js configuration to parse the URL.\n */\n nextConfig?: {\n basePath?: string\n i18n?: { locales?: readonly string[] } | null\n trailingSlash?: boolean\n }\n\n /**\n * If provided, this normalizer will be used to detect the locale instead of\n * the default locale detection.\n */\n i18nProvider?: I18NProvider\n}\n\nexport function getNextPathnameInfo(\n pathname: string,\n options: Options\n): NextPathnameInfo {\n const { basePath, i18n, trailingSlash } = options.nextConfig ?? {}\n const info: NextPathnameInfo = {\n pathname,\n trailingSlash: pathname !== '/' ? pathname.endsWith('/') : trailingSlash,\n }\n\n if (basePath && pathHasPrefix(info.pathname, basePath)) {\n info.pathname = removePathPrefix(info.pathname, basePath)\n info.basePath = basePath\n }\n let pathnameNoDataPrefix = info.pathname\n\n if (\n info.pathname.startsWith('/_next/data/') &&\n info.pathname.endsWith('.json')\n ) {\n const paths = info.pathname\n .replace(/^\\/_next\\/data\\//, '')\n .replace(/\\.json$/, '')\n .split('/')\n\n const buildId = paths[0]\n info.buildId = buildId\n pathnameNoDataPrefix =\n paths[1] !== 'index' ? `/${paths.slice(1).join('/')}` : '/'\n\n // update pathname with normalized if enabled although\n // we use normalized to populate locale info still\n if (options.parseData === true) {\n info.pathname = pathnameNoDataPrefix\n }\n }\n\n // If provided, use the locale route normalizer to detect the locale instead\n // of the function below.\n if (i18n) {\n let result = options.i18nProvider\n ? options.i18nProvider.analyze(info.pathname)\n : normalizeLocalePath(info.pathname, i18n.locales)\n\n info.locale = result.detectedLocale\n info.pathname = result.pathname ?? info.pathname\n\n if (!result.detectedLocale && info.buildId) {\n result = options.i18nProvider\n ? options.i18nProvider.analyze(pathnameNoDataPrefix)\n : normalizeLocalePath(pathnameNoDataPrefix, i18n.locales)\n\n if (result.detectedLocale) {\n info.locale = result.detectedLocale\n }\n }\n }\n return info\n}\n"],"names":["getNextPathnameInfo","pathname","options","basePath","i18n","trailingSlash","nextConfig","info","endsWith","pathHasPrefix","removePathPrefix","pathnameNoDataPrefix","startsWith","paths","replace","split","buildId","slice","join","parseData","result","i18nProvider","analyze","normalizeLocalePath","locales","locale","detectedLocale"],"mappings":";;;;+BAoDgBA;;;eAAAA;;;qCApDoB;kCACH;+BACH;AAkDvB,SAASA,oBACdC,QAAgB,EAChBC,OAAgB;IAEhB,MAAM,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,aAAa,EAAE,GAAGH,QAAQI,UAAU,IAAI,CAAC;IACjE,MAAMC,OAAyB;QAC7BN;QACAI,eAAeJ,aAAa,MAAMA,SAASO,QAAQ,CAAC,OAAOH;IAC7D;IAEA,IAAIF,YAAYM,IAAAA,4BAAa,EAACF,KAAKN,QAAQ,EAAEE,WAAW;QACtDI,KAAKN,QAAQ,GAAGS,IAAAA,kCAAgB,EAACH,KAAKN,QAAQ,EAAEE;QAChDI,KAAKJ,QAAQ,GAAGA;IAClB;IACA,IAAIQ,uBAAuBJ,KAAKN,QAAQ;IAExC,IACEM,KAAKN,QAAQ,CAACW,UAAU,CAAC,mBACzBL,KAAKN,QAAQ,CAACO,QAAQ,CAAC,UACvB;QACA,MAAMK,QAAQN,KAAKN,QAAQ,CACxBa,OAAO,CAAC,oBAAoB,IAC5BA,OAAO,CAAC,WAAW,IACnBC,KAAK,CAAC;QAET,MAAMC,UAAUH,KAAK,CAAC,EAAE;QACxBN,KAAKS,OAAO,GAAGA;QACfL,uBACEE,KAAK,CAAC,EAAE,KAAK,UAAU,CAAC,CAAC,EAAEA,MAAMI,KAAK,CAAC,GAAGC,IAAI,CAAC,MAAM,GAAG;QAE1D,sDAAsD;QACtD,kDAAkD;QAClD,IAAIhB,QAAQiB,SAAS,KAAK,MAAM;YAC9BZ,KAAKN,QAAQ,GAAGU;QAClB;IACF;IAEA,4EAA4E;IAC5E,yBAAyB;IACzB,IAAIP,MAAM;QACR,IAAIgB,SAASlB,QAAQmB,YAAY,GAC7BnB,QAAQmB,YAAY,CAACC,OAAO,CAACf,KAAKN,QAAQ,IAC1CsB,IAAAA,wCAAmB,EAAChB,KAAKN,QAAQ,EAAEG,KAAKoB,OAAO;QAEnDjB,KAAKkB,MAAM,GAAGL,OAAOM,cAAc;QACnCnB,KAAKN,QAAQ,GAAGmB,OAAOnB,QAAQ,IAAIM,KAAKN,QAAQ;QAEhD,IAAI,CAACmB,OAAOM,cAAc,IAAInB,KAAKS,OAAO,EAAE;YAC1CI,SAASlB,QAAQmB,YAAY,GACzBnB,QAAQmB,YAAY,CAACC,OAAO,CAACX,wBAC7BY,IAAAA,wCAAmB,EAACZ,sBAAsBP,KAAKoB,OAAO;YAE1D,IAAIJ,OAAOM,cAAc,EAAE;gBACzBnB,KAAKkB,MAAM,GAAGL,OAAOM,cAAc;YACrC;QACF;IACF;IACA,OAAOnB;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c624ff242ab67aa95d00f3d3f772cd67b8fd23ff --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.d.ts @@ -0,0 +1 @@ +export default function getRouteFromAssetPath(assetPath: string, ext?: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js new file mode 100644 index 0000000000000000000000000000000000000000..1563892d4c8a8bd5ed0e6820306d16a68c816c9f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js @@ -0,0 +1,25 @@ +// Translate a pages asset path (relative from a common prefix) back into its logical route +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, // "asset path" being its javascript file, data file, prerendered html,... +"default", { + enumerable: true, + get: function() { + return getRouteFromAssetPath; + } +}); +const _isdynamic = require("./is-dynamic"); +function getRouteFromAssetPath(assetPath, ext = '') { + assetPath = assetPath.replace(/\\/g, '/'); + assetPath = ext && assetPath.endsWith(ext) ? assetPath.slice(0, -ext.length) : assetPath; + if (assetPath.startsWith('/index/') && !(0, _isdynamic.isDynamicRoute)(assetPath)) { + assetPath = assetPath.slice(6); + } else if (assetPath === '/index') { + assetPath = '/'; + } + return assetPath; +} + +//# sourceMappingURL=get-route-from-asset-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b01674424dcdc726e99de3f356e44b13a6c89cd0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/get-route-from-asset-path.ts"],"sourcesContent":["// Translate a pages asset path (relative from a common prefix) back into its logical route\n\nimport { isDynamicRoute } from './is-dynamic'\n\n// \"asset path\" being its javascript file, data file, prerendered html,...\nexport default function getRouteFromAssetPath(\n assetPath: string,\n ext: string = ''\n): string {\n assetPath = assetPath.replace(/\\\\/g, '/')\n assetPath =\n ext && assetPath.endsWith(ext) ? assetPath.slice(0, -ext.length) : assetPath\n if (assetPath.startsWith('/index/') && !isDynamicRoute(assetPath)) {\n assetPath = assetPath.slice(6)\n } else if (assetPath === '/index') {\n assetPath = '/'\n }\n return assetPath\n}\n"],"names":["getRouteFromAssetPath","assetPath","ext","replace","endsWith","slice","length","startsWith","isDynamicRoute"],"mappings":"AAAA,2FAA2F;;;;;+BAI3F,0EAA0E;AAC1E;;;eAAwBA;;;2BAHO;AAGhB,SAASA,sBACtBC,SAAiB,EACjBC,MAAc,EAAE;IAEhBD,YAAYA,UAAUE,OAAO,CAAC,OAAO;IACrCF,YACEC,OAAOD,UAAUG,QAAQ,CAACF,OAAOD,UAAUI,KAAK,CAAC,GAAG,CAACH,IAAII,MAAM,IAAIL;IACrE,IAAIA,UAAUM,UAAU,CAAC,cAAc,CAACC,IAAAA,yBAAc,EAACP,YAAY;QACjEA,YAAYA,UAAUI,KAAK,CAAC;IAC9B,OAAO,IAAIJ,cAAc,UAAU;QACjCA,YAAY;IACd;IACA,OAAOA;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..340521d5846a78d8cc5c5c7edf97d6d17e2c8ff6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.d.ts @@ -0,0 +1,14 @@ +import type { DynamicParamTypes } from '../../app-router-types'; +export type SegmentParam = { + paramName: string; + paramType: DynamicParamTypes; +}; +/** + * Parse dynamic route segment to type of parameter + */ +export declare function getSegmentParam(segment: string): SegmentParam | null; +export declare function isCatchAll(type: DynamicParamTypes): type is 'catchall' | 'catchall-intercepted-(..)(..)' | 'catchall-intercepted-(.)' | 'catchall-intercepted-(..)' | 'catchall-intercepted-(...)' | 'optional-catchall'; +export declare function getParamProperties(paramType: DynamicParamTypes): { + repeat: boolean; + optional: boolean; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.js new file mode 100644 index 0000000000000000000000000000000000000000..d3ad699ec920c65f3653bbd717f9623f09dab34c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getParamProperties: null, + getSegmentParam: null, + isCatchAll: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getParamProperties: function() { + return getParamProperties; + }, + getSegmentParam: function() { + return getSegmentParam; + }, + isCatchAll: function() { + return isCatchAll; + } +}); +const _interceptionroutes = require("./interception-routes"); +function getSegmentParam(segment) { + const interceptionMarker = _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.find((marker)=>segment.startsWith(marker)); + // if an interception marker is part of the path segment, we need to jump ahead + // to the relevant portion for param parsing + if (interceptionMarker) { + segment = segment.slice(interceptionMarker.length); + } + if (segment.startsWith('[[...') && segment.endsWith(']]')) { + return { + // TODO-APP: Optional catchall does not currently work with parallel routes, + // so for now aren't handling a potential interception marker. + paramType: 'optional-catchall', + paramName: segment.slice(5, -2) + }; + } + if (segment.startsWith('[...') && segment.endsWith(']')) { + return { + paramType: interceptionMarker ? `catchall-intercepted-${interceptionMarker}` : 'catchall', + paramName: segment.slice(4, -1) + }; + } + if (segment.startsWith('[') && segment.endsWith(']')) { + return { + paramType: interceptionMarker ? `dynamic-intercepted-${interceptionMarker}` : 'dynamic', + paramName: segment.slice(1, -1) + }; + } + return null; +} +function isCatchAll(type) { + return type === 'catchall' || type === 'catchall-intercepted-(..)(..)' || type === 'catchall-intercepted-(.)' || type === 'catchall-intercepted-(..)' || type === 'catchall-intercepted-(...)' || type === 'optional-catchall'; +} +function getParamProperties(paramType) { + let repeat = false; + let optional = false; + switch(paramType){ + case 'catchall': + case 'catchall-intercepted-(..)(..)': + case 'catchall-intercepted-(.)': + case 'catchall-intercepted-(..)': + case 'catchall-intercepted-(...)': + repeat = true; + break; + case 'optional-catchall': + repeat = true; + optional = true; + break; + case 'dynamic': + case 'dynamic-intercepted-(..)(..)': + case 'dynamic-intercepted-(.)': + case 'dynamic-intercepted-(..)': + case 'dynamic-intercepted-(...)': + break; + default: + paramType; + } + return { + repeat, + optional + }; +} + +//# sourceMappingURL=get-segment-param.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.js.map new file mode 100644 index 0000000000000000000000000000000000000000..42a8b5cfcfbaa585936a32d749be0e0cf03887e8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/get-segment-param.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/get-segment-param.tsx"],"sourcesContent":["import { INTERCEPTION_ROUTE_MARKERS } from './interception-routes'\nimport type { DynamicParamTypes } from '../../app-router-types'\n\nexport type SegmentParam = {\n paramName: string\n paramType: DynamicParamTypes\n}\n\n/**\n * Parse dynamic route segment to type of parameter\n */\nexport function getSegmentParam(segment: string): SegmentParam | null {\n const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((marker) =>\n segment.startsWith(marker)\n )\n\n // if an interception marker is part of the path segment, we need to jump ahead\n // to the relevant portion for param parsing\n if (interceptionMarker) {\n segment = segment.slice(interceptionMarker.length)\n }\n\n if (segment.startsWith('[[...') && segment.endsWith(']]')) {\n return {\n // TODO-APP: Optional catchall does not currently work with parallel routes,\n // so for now aren't handling a potential interception marker.\n paramType: 'optional-catchall',\n paramName: segment.slice(5, -2),\n }\n }\n\n if (segment.startsWith('[...') && segment.endsWith(']')) {\n return {\n paramType: interceptionMarker\n ? `catchall-intercepted-${interceptionMarker}`\n : 'catchall',\n paramName: segment.slice(4, -1),\n }\n }\n\n if (segment.startsWith('[') && segment.endsWith(']')) {\n return {\n paramType: interceptionMarker\n ? `dynamic-intercepted-${interceptionMarker}`\n : 'dynamic',\n paramName: segment.slice(1, -1),\n }\n }\n\n return null\n}\n\nexport function isCatchAll(\n type: DynamicParamTypes\n): type is\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall' {\n return (\n type === 'catchall' ||\n type === 'catchall-intercepted-(..)(..)' ||\n type === 'catchall-intercepted-(.)' ||\n type === 'catchall-intercepted-(..)' ||\n type === 'catchall-intercepted-(...)' ||\n type === 'optional-catchall'\n )\n}\n\nexport function getParamProperties(paramType: DynamicParamTypes): {\n repeat: boolean\n optional: boolean\n} {\n let repeat = false\n let optional = false\n\n switch (paramType) {\n case 'catchall':\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n repeat = true\n break\n case 'optional-catchall':\n repeat = true\n optional = true\n break\n case 'dynamic':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)':\n break\n default:\n paramType satisfies never\n }\n\n return { repeat, optional }\n}\n"],"names":["getParamProperties","getSegmentParam","isCatchAll","segment","interceptionMarker","INTERCEPTION_ROUTE_MARKERS","find","marker","startsWith","slice","length","endsWith","paramType","paramName","type","repeat","optional"],"mappings":";;;;;;;;;;;;;;;;IAuEgBA,kBAAkB;eAAlBA;;IA5DAC,eAAe;eAAfA;;IAyCAC,UAAU;eAAVA;;;oCApD2B;AAWpC,SAASD,gBAAgBE,OAAe;IAC7C,MAAMC,qBAAqBC,8CAA0B,CAACC,IAAI,CAAC,CAACC,SAC1DJ,QAAQK,UAAU,CAACD;IAGrB,+EAA+E;IAC/E,4CAA4C;IAC5C,IAAIH,oBAAoB;QACtBD,UAAUA,QAAQM,KAAK,CAACL,mBAAmBM,MAAM;IACnD;IAEA,IAAIP,QAAQK,UAAU,CAAC,YAAYL,QAAQQ,QAAQ,CAAC,OAAO;QACzD,OAAO;YACL,4EAA4E;YAC5E,8DAA8D;YAC9DC,WAAW;YACXC,WAAWV,QAAQM,KAAK,CAAC,GAAG,CAAC;QAC/B;IACF;IAEA,IAAIN,QAAQK,UAAU,CAAC,WAAWL,QAAQQ,QAAQ,CAAC,MAAM;QACvD,OAAO;YACLC,WAAWR,qBACP,CAAC,qBAAqB,EAAEA,oBAAoB,GAC5C;YACJS,WAAWV,QAAQM,KAAK,CAAC,GAAG,CAAC;QAC/B;IACF;IAEA,IAAIN,QAAQK,UAAU,CAAC,QAAQL,QAAQQ,QAAQ,CAAC,MAAM;QACpD,OAAO;YACLC,WAAWR,qBACP,CAAC,oBAAoB,EAAEA,oBAAoB,GAC3C;YACJS,WAAWV,QAAQM,KAAK,CAAC,GAAG,CAAC;QAC/B;IACF;IAEA,OAAO;AACT;AAEO,SAASP,WACdY,IAAuB;IAQvB,OACEA,SAAS,cACTA,SAAS,mCACTA,SAAS,8BACTA,SAAS,+BACTA,SAAS,gCACTA,SAAS;AAEb;AAEO,SAASd,mBAAmBY,SAA4B;IAI7D,IAAIG,SAAS;IACb,IAAIC,WAAW;IAEf,OAAQJ;QACN,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACHG,SAAS;YACT;QACF,KAAK;YACHA,SAAS;YACTC,WAAW;YACX;QACF,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEJ;IACJ;IAEA,OAAO;QAAEG;QAAQC;IAAS;AAC5B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bf5db7e0f3d2090e277f0f0d432daa49416e311 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.d.ts @@ -0,0 +1 @@ +export declare const HTML_LIMITED_BOT_UA_RE: RegExp; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.js new file mode 100644 index 0000000000000000000000000000000000000000..54a41f4c19120f3da0a7e3a1b95b87be043d40a9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.js @@ -0,0 +1,17 @@ +// This regex contains the bots that we need to do a blocking render for and can't safely stream the response +// due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent. +// Note: The pattern [\w-]+-Google captures all Google crawlers with "-Google" suffix (e.g., Mediapartners-Google, AdsBot-Google, Storebot-Google) +// as well as crawlers starting with "Google-" (e.g., Google-PageRenderer, Google-InspectionTool) +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "HTML_LIMITED_BOT_UA_RE", { + enumerable: true, + get: function() { + return HTML_LIMITED_BOT_UA_RE; + } +}); +const HTML_LIMITED_BOT_UA_RE = /[\w-]+-Google|Google-[\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight/i; + +//# sourceMappingURL=html-bots.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.js.map new file mode 100644 index 0000000000000000000000000000000000000000..46f89bb3377934c826f2fee1cfa7919cfcedf9b3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/html-bots.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/html-bots.ts"],"sourcesContent":["// This regex contains the bots that we need to do a blocking render for and can't safely stream the response\n// due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent.\n// Note: The pattern [\\w-]+-Google captures all Google crawlers with \"-Google\" suffix (e.g., Mediapartners-Google, AdsBot-Google, Storebot-Google)\n// as well as crawlers starting with \"Google-\" (e.g., Google-PageRenderer, Google-InspectionTool)\nexport const HTML_LIMITED_BOT_UA_RE =\n /[\\w-]+-Google|Google-[\\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight/i\n"],"names":["HTML_LIMITED_BOT_UA_RE"],"mappings":"AAAA,6GAA6G;AAC7G,sKAAsK;AACtK,kJAAkJ;AAClJ,iGAAiG;;;;;+BACpFA;;;eAAAA;;;AAAN,MAAMA,yBACX","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b52fa197268fbcd7fec2916a208f4024e746a6bd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.d.ts @@ -0,0 +1,2 @@ +export { getSortedRoutes, getSortedRouteObjects } from './sorted-routes'; +export { isDynamicRoute } from './is-dynamic'; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..42ad00cc11fdd81e98e1cfc7d74e389a30648314 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getSortedRouteObjects: null, + getSortedRoutes: null, + isDynamicRoute: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getSortedRouteObjects: function() { + return _sortedroutes.getSortedRouteObjects; + }, + getSortedRoutes: function() { + return _sortedroutes.getSortedRoutes; + }, + isDynamicRoute: function() { + return _isdynamic.isDynamicRoute; + } +}); +const _sortedroutes = require("./sorted-routes"); +const _isdynamic = require("./is-dynamic"); + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d67d72d7048015a55f0a27b3d644e9a81060fd15 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/index.ts"],"sourcesContent":["export { getSortedRoutes, getSortedRouteObjects } from './sorted-routes'\nexport { isDynamicRoute } from './is-dynamic'\n"],"names":["getSortedRouteObjects","getSortedRoutes","isDynamicRoute"],"mappings":";;;;;;;;;;;;;;;;IAA0BA,qBAAqB;eAArBA,mCAAqB;;IAAtCC,eAAe;eAAfA,6BAAe;;IACfC,cAAc;eAAdA,yBAAc;;;8BADgC;2BACxB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..93b7601ecd427548d37933fb7ccabfccd50c7c41 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.d.ts @@ -0,0 +1,2 @@ +import type { DynamicParamTypes } from '../../app-router-types'; +export declare function interceptionPrefixFromParamType(paramType: DynamicParamTypes): string | null; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.js new file mode 100644 index 0000000000000000000000000000000000000000..df11076d37a44714e234e3cf2f2be9fe1f9191b2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "interceptionPrefixFromParamType", { + enumerable: true, + get: function() { + return interceptionPrefixFromParamType; + } +}); +function interceptionPrefixFromParamType(paramType) { + switch(paramType){ + case 'catchall-intercepted-(..)(..)': + case 'dynamic-intercepted-(..)(..)': + return '(..)(..)'; + case 'catchall-intercepted-(.)': + case 'dynamic-intercepted-(.)': + return '(.)'; + case 'catchall-intercepted-(..)': + case 'dynamic-intercepted-(..)': + return '(..)'; + case 'catchall-intercepted-(...)': + case 'dynamic-intercepted-(...)': + return '(...)'; + case 'catchall': + case 'dynamic': + case 'optional-catchall': + default: + return null; + } +} + +//# sourceMappingURL=interception-prefix-from-param-type.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c8e42394e07c649c7c917b57b71682b878260d52 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-prefix-from-param-type.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/interception-prefix-from-param-type.ts"],"sourcesContent":["import type { DynamicParamTypes } from '../../app-router-types'\n\nexport function interceptionPrefixFromParamType(\n paramType: DynamicParamTypes\n): string | null {\n switch (paramType) {\n case 'catchall-intercepted-(..)(..)':\n case 'dynamic-intercepted-(..)(..)':\n return '(..)(..)'\n case 'catchall-intercepted-(.)':\n case 'dynamic-intercepted-(.)':\n return '(.)'\n case 'catchall-intercepted-(..)':\n case 'dynamic-intercepted-(..)':\n return '(..)'\n case 'catchall-intercepted-(...)':\n case 'dynamic-intercepted-(...)':\n return '(...)'\n case 'catchall':\n case 'dynamic':\n case 'optional-catchall':\n default:\n return null\n }\n}\n"],"names":["interceptionPrefixFromParamType","paramType"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAAT,SAASA,gCACdC,SAA4B;IAE5B,OAAQA;QACN,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;QACL,KAAK;QACL;YACE,OAAO;IACX;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9dee949c5efb4fe872b43a5bee898ada91278e60 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.d.ts @@ -0,0 +1,29 @@ +export declare const INTERCEPTION_ROUTE_MARKERS: readonly ["(..)(..)", "(.)", "(..)", "(...)"]; +export type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]; +export type MissingCanonicalInterceptionRoute = { + interceptionRoute: string; + canonicalRoute: string; +}; +export declare function isInterceptionRouteAppPath(path: string): boolean; +type InterceptionRouteInformation = { + /** + * The intercepting route. This is the route that is being intercepted or the + * route that the user was coming from. This is matched by the Next-Url + * header. + */ + interceptingRoute: string; + /** + * The intercepted route. This is the route that is being intercepted or the + * route that the user is going to. This is matched by the request pathname. + */ + interceptedRoute: string; +}; +export declare function extractInterceptionRouteInformation(path: string): InterceptionRouteInformation; +/** + * Finds interception matchers that cannot be loaded as an ordinary request. + * + * This must run after catch-all normalization and pruning so `appPaths` + * contains the final matcher set rather than every possible matcher candidate. + */ +export declare function findMissingCanonicalInterceptionRoutes(appPaths: Record): MissingCanonicalInterceptionRoute[]; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.js new file mode 100644 index 0000000000000000000000000000000000000000..3b8cb090f1b183e0a7b99b6fb88efc340f785625 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.js @@ -0,0 +1,151 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + INTERCEPTION_ROUTE_MARKERS: null, + extractInterceptionRouteInformation: null, + findMissingCanonicalInterceptionRoutes: null, + isInterceptionRouteAppPath: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + INTERCEPTION_ROUTE_MARKERS: function() { + return INTERCEPTION_ROUTE_MARKERS; + }, + extractInterceptionRouteInformation: function() { + return extractInterceptionRouteInformation; + }, + findMissingCanonicalInterceptionRoutes: function() { + return findMissingCanonicalInterceptionRoutes; + }, + isInterceptionRouteAppPath: function() { + return isInterceptionRouteAppPath; + } +}); +const _apppaths = require("./app-paths"); +const INTERCEPTION_ROUTE_MARKERS = [ + '(..)(..)', + '(.)', + '(..)', + '(...)' +]; +function parseRoutePattern(route) { + const segments = route.split('/').filter(Boolean); + const tail = segments.at(-1); + const isOptionalCatchAll = tail !== undefined && tail.startsWith('[[...') && tail.endsWith(']]'); + const isCatchAll = tail !== undefined && tail.startsWith('[...') && tail.endsWith(']'); + const unbounded = isOptionalCatchAll || isCatchAll; + const prefixSegments = unbounded ? segments.slice(0, -1) : segments; + return { + prefix: prefixSegments.map((segment)=>segment.startsWith('[') && segment.endsWith(']') ? null : segment), + minLength: prefixSegments.length + (isCatchAll && !isOptionalCatchAll ? 1 : 0), + unbounded + }; +} +function acceptsLength(pattern, length) { + return pattern.unbounded ? length >= pattern.minLength : length === pattern.minLength; +} +function prefixCovers(canonical, intercepted) { + return canonical.prefix.every((canonicalSegment, index)=>{ + if (canonicalSegment === null) return true; + const interceptedSegment = intercepted.prefix[index]; + return interceptedSegment !== undefined && interceptedSegment !== null && canonicalSegment === interceptedSegment; + }); +} +function patternCoversAtLength(canonical, intercepted, length) { + return acceptsLength(canonical, length) && acceptsLength(intercepted, length) && prefixCovers(canonical, intercepted); +} +/** Returns whether ordinary route patterns cover every URL in `route`. */ function isRoutePatternCovered(route, ordinaryRoutes) { + const intercepted = parseRoutePattern(route); + if (!intercepted.unbounded) { + return ordinaryRoutes.some((pattern)=>patternCoversAtLength(pattern, intercepted, intercepted.minLength)); + } + let unboundedCoverageStart = Infinity; + for (const pattern of ordinaryRoutes){ + if (pattern.unbounded && prefixCovers(pattern, intercepted)) { + unboundedCoverageStart = Math.min(unboundedCoverageStart, Math.max(intercepted.minLength, pattern.minLength)); + } + } + if (unboundedCoverageStart === Infinity) return false; + // An optional or required catchall can have its shorter paths covered by + // fixed routes before another catchall takes over the remaining suffix. + for(let length = intercepted.minLength; length < unboundedCoverageStart; length++){ + if (!ordinaryRoutes.some((pattern)=>patternCoversAtLength(pattern, intercepted, length))) { + return false; + } + } + return true; +} +function isInterceptionRouteAppPath(path) { + // TODO-APP: add more serious validation + return path.split('/').find((segment)=>INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m))) !== undefined; +} +function extractInterceptionRouteInformation(path) { + let interceptingRoute; + let marker; + let interceptedRoute; + for (const segment of path.split('/')){ + marker = INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m)); + if (marker) { + ; + [interceptingRoute, interceptedRoute] = path.split(marker, 2); + break; + } + } + if (!interceptingRoute || !marker || !interceptedRoute) { + throw new Error(`Invalid interception route: ${path}. Must be in the format //(..|...|..)(..)/`); + } + interceptingRoute = (0, _apppaths.normalizeAppPath)(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed + ; + switch(marker){ + case '(.)': + // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route + if (interceptingRoute === '/') { + interceptedRoute = `/${interceptedRoute}`; + } else { + interceptedRoute = interceptingRoute + '/' + interceptedRoute; + } + break; + case '(..)': + // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route + if (interceptingRoute === '/') { + throw new Error(`Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`); + } + interceptedRoute = interceptingRoute.split('/').slice(0, -1).concat(interceptedRoute).join('/'); + break; + case '(...)': + // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route + interceptedRoute = '/' + interceptedRoute; + break; + case '(..)(..)': + // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route + const splitInterceptingRoute = interceptingRoute.split('/'); + if (splitInterceptingRoute.length <= 2) { + throw new Error(`Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`); + } + interceptedRoute = splitInterceptingRoute.slice(0, -2).concat(interceptedRoute).join('/'); + break; + default: + throw new Error('Invariant: unexpected marker'); + } + return { + interceptingRoute, + interceptedRoute + }; +} +function findMissingCanonicalInterceptionRoutes(appPaths) { + const canonicalRoutes = Object.keys(appPaths).filter((route)=>!isInterceptionRouteAppPath(route)); + const canonicalRoutePatterns = canonicalRoutes.map(parseRoutePattern); + return Object.keys(appPaths).filter(isInterceptionRouteAppPath).map((interceptionRoute)=>({ + interceptionRoute, + canonicalRoute: extractInterceptionRouteInformation(interceptionRoute).interceptedRoute + })).filter(({ canonicalRoute })=>!isRoutePatternCovered(canonicalRoute, canonicalRoutePatterns)).sort((a, b)=>a.interceptionRoute.localeCompare(b.interceptionRoute)); +} + +//# sourceMappingURL=interception-routes.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7f273e867777d290bc1cdd10cb5fb10eace5b809 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interception-routes.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/interception-routes.ts"],"sourcesContent":["import { normalizeAppPath } from './app-paths'\n\n// order matters here, the first match will be used\nexport const INTERCEPTION_ROUTE_MARKERS = [\n '(..)(..)',\n '(.)',\n '(..)',\n '(...)',\n] as const\n\nexport type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]\n\nexport type MissingCanonicalInterceptionRoute = {\n interceptionRoute: string\n canonicalRoute: string\n}\n\ntype RoutePattern = {\n prefix: Array\n minLength: number\n unbounded: boolean\n}\n\nfunction parseRoutePattern(route: string): RoutePattern {\n const segments = route.split('/').filter(Boolean)\n const tail = segments.at(-1)\n const isOptionalCatchAll =\n tail !== undefined && tail.startsWith('[[...') && tail.endsWith(']]')\n const isCatchAll =\n tail !== undefined && tail.startsWith('[...') && tail.endsWith(']')\n const unbounded = isOptionalCatchAll || isCatchAll\n const prefixSegments = unbounded ? segments.slice(0, -1) : segments\n\n return {\n prefix: prefixSegments.map((segment) =>\n segment.startsWith('[') && segment.endsWith(']') ? null : segment\n ),\n minLength:\n prefixSegments.length + (isCatchAll && !isOptionalCatchAll ? 1 : 0),\n unbounded,\n }\n}\n\nfunction acceptsLength(pattern: RoutePattern, length: number): boolean {\n return pattern.unbounded\n ? length >= pattern.minLength\n : length === pattern.minLength\n}\n\nfunction prefixCovers(\n canonical: RoutePattern,\n intercepted: RoutePattern\n): boolean {\n return canonical.prefix.every((canonicalSegment, index) => {\n if (canonicalSegment === null) return true\n\n const interceptedSegment = intercepted.prefix[index]\n return (\n interceptedSegment !== undefined &&\n interceptedSegment !== null &&\n canonicalSegment === interceptedSegment\n )\n })\n}\n\nfunction patternCoversAtLength(\n canonical: RoutePattern,\n intercepted: RoutePattern,\n length: number\n): boolean {\n return (\n acceptsLength(canonical, length) &&\n acceptsLength(intercepted, length) &&\n prefixCovers(canonical, intercepted)\n )\n}\n\n/** Returns whether ordinary route patterns cover every URL in `route`. */\nfunction isRoutePatternCovered(route: string, ordinaryRoutes: RoutePattern[]) {\n const intercepted = parseRoutePattern(route)\n\n if (!intercepted.unbounded) {\n return ordinaryRoutes.some((pattern) =>\n patternCoversAtLength(pattern, intercepted, intercepted.minLength)\n )\n }\n\n let unboundedCoverageStart = Infinity\n for (const pattern of ordinaryRoutes) {\n if (pattern.unbounded && prefixCovers(pattern, intercepted)) {\n unboundedCoverageStart = Math.min(\n unboundedCoverageStart,\n Math.max(intercepted.minLength, pattern.minLength)\n )\n }\n }\n\n if (unboundedCoverageStart === Infinity) return false\n\n // An optional or required catchall can have its shorter paths covered by\n // fixed routes before another catchall takes over the remaining suffix.\n for (\n let length = intercepted.minLength;\n length < unboundedCoverageStart;\n length++\n ) {\n if (\n !ordinaryRoutes.some((pattern) =>\n patternCoversAtLength(pattern, intercepted, length)\n )\n ) {\n return false\n }\n }\n\n return true\n}\n\nexport function isInterceptionRouteAppPath(path: string): boolean {\n // TODO-APP: add more serious validation\n return (\n path\n .split('/')\n .find((segment) =>\n INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n ) !== undefined\n )\n}\n\ntype InterceptionRouteInformation = {\n /**\n * The intercepting route. This is the route that is being intercepted or the\n * route that the user was coming from. This is matched by the Next-Url\n * header.\n */\n interceptingRoute: string\n\n /**\n * The intercepted route. This is the route that is being intercepted or the\n * route that the user is going to. This is matched by the request pathname.\n */\n interceptedRoute: string\n}\n\nexport function extractInterceptionRouteInformation(\n path: string\n): InterceptionRouteInformation {\n let interceptingRoute: string | undefined\n let marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined\n let interceptedRoute: string | undefined\n\n for (const segment of path.split('/')) {\n marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n if (marker) {\n ;[interceptingRoute, interceptedRoute] = path.split(marker, 2)\n break\n }\n }\n\n if (!interceptingRoute || !marker || !interceptedRoute) {\n throw new Error(\n `Invalid interception route: ${path}. Must be in the format //(..|...|..)(..)/`\n )\n }\n\n interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed\n\n switch (marker) {\n case '(.)':\n // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route\n if (interceptingRoute === '/') {\n interceptedRoute = `/${interceptedRoute}`\n } else {\n interceptedRoute = interceptingRoute + '/' + interceptedRoute\n }\n break\n case '(..)':\n // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route\n if (interceptingRoute === '/') {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`\n )\n }\n interceptedRoute = interceptingRoute\n .split('/')\n .slice(0, -1)\n .concat(interceptedRoute)\n .join('/')\n break\n case '(...)':\n // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route\n interceptedRoute = '/' + interceptedRoute\n break\n case '(..)(..)':\n // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route\n\n const splitInterceptingRoute = interceptingRoute.split('/')\n if (splitInterceptingRoute.length <= 2) {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`\n )\n }\n\n interceptedRoute = splitInterceptingRoute\n .slice(0, -2)\n .concat(interceptedRoute)\n .join('/')\n break\n default:\n throw new Error('Invariant: unexpected marker')\n }\n\n return { interceptingRoute, interceptedRoute }\n}\n\n/**\n * Finds interception matchers that cannot be loaded as an ordinary request.\n *\n * This must run after catch-all normalization and pruning so `appPaths`\n * contains the final matcher set rather than every possible matcher candidate.\n */\nexport function findMissingCanonicalInterceptionRoutes(\n appPaths: Record\n): MissingCanonicalInterceptionRoute[] {\n const canonicalRoutes = Object.keys(appPaths).filter(\n (route) => !isInterceptionRouteAppPath(route)\n )\n const canonicalRoutePatterns = canonicalRoutes.map(parseRoutePattern)\n\n return Object.keys(appPaths)\n .filter(isInterceptionRouteAppPath)\n .map((interceptionRoute) => ({\n interceptionRoute,\n canonicalRoute:\n extractInterceptionRouteInformation(interceptionRoute).interceptedRoute,\n }))\n .filter(\n ({ canonicalRoute }) =>\n !isRoutePatternCovered(canonicalRoute, canonicalRoutePatterns)\n )\n .sort((a, b) => a.interceptionRoute.localeCompare(b.interceptionRoute))\n}\n"],"names":["INTERCEPTION_ROUTE_MARKERS","extractInterceptionRouteInformation","findMissingCanonicalInterceptionRoutes","isInterceptionRouteAppPath","parseRoutePattern","route","segments","split","filter","Boolean","tail","at","isOptionalCatchAll","undefined","startsWith","endsWith","isCatchAll","unbounded","prefixSegments","slice","prefix","map","segment","minLength","length","acceptsLength","pattern","prefixCovers","canonical","intercepted","every","canonicalSegment","index","interceptedSegment","patternCoversAtLength","isRoutePatternCovered","ordinaryRoutes","some","unboundedCoverageStart","Infinity","Math","min","max","path","find","m","interceptingRoute","marker","interceptedRoute","Error","normalizeAppPath","concat","join","splitInterceptingRoute","appPaths","canonicalRoutes","Object","keys","canonicalRoutePatterns","interceptionRoute","canonicalRoute","sort","a","b","localeCompare"],"mappings":";;;;;;;;;;;;;;;;;IAGaA,0BAA0B;eAA1BA;;IA6IGC,mCAAmC;eAAnCA;;IA6EAC,sCAAsC;eAAtCA;;IAvGAC,0BAA0B;eAA1BA;;;0BAtHiB;AAG1B,MAAMH,6BAA6B;IACxC;IACA;IACA;IACA;CACD;AAeD,SAASI,kBAAkBC,KAAa;IACtC,MAAMC,WAAWD,MAAME,KAAK,CAAC,KAAKC,MAAM,CAACC;IACzC,MAAMC,OAAOJ,SAASK,EAAE,CAAC,CAAC;IAC1B,MAAMC,qBACJF,SAASG,aAAaH,KAAKI,UAAU,CAAC,YAAYJ,KAAKK,QAAQ,CAAC;IAClE,MAAMC,aACJN,SAASG,aAAaH,KAAKI,UAAU,CAAC,WAAWJ,KAAKK,QAAQ,CAAC;IACjE,MAAME,YAAYL,sBAAsBI;IACxC,MAAME,iBAAiBD,YAAYX,SAASa,KAAK,CAAC,GAAG,CAAC,KAAKb;IAE3D,OAAO;QACLc,QAAQF,eAAeG,GAAG,CAAC,CAACC,UAC1BA,QAAQR,UAAU,CAAC,QAAQQ,QAAQP,QAAQ,CAAC,OAAO,OAAOO;QAE5DC,WACEL,eAAeM,MAAM,GAAIR,CAAAA,cAAc,CAACJ,qBAAqB,IAAI,CAAA;QACnEK;IACF;AACF;AAEA,SAASQ,cAAcC,OAAqB,EAAEF,MAAc;IAC1D,OAAOE,QAAQT,SAAS,GACpBO,UAAUE,QAAQH,SAAS,GAC3BC,WAAWE,QAAQH,SAAS;AAClC;AAEA,SAASI,aACPC,SAAuB,EACvBC,WAAyB;IAEzB,OAAOD,UAAUR,MAAM,CAACU,KAAK,CAAC,CAACC,kBAAkBC;QAC/C,IAAID,qBAAqB,MAAM,OAAO;QAEtC,MAAME,qBAAqBJ,YAAYT,MAAM,CAACY,MAAM;QACpD,OACEC,uBAAuBpB,aACvBoB,uBAAuB,QACvBF,qBAAqBE;IAEzB;AACF;AAEA,SAASC,sBACPN,SAAuB,EACvBC,WAAyB,EACzBL,MAAc;IAEd,OACEC,cAAcG,WAAWJ,WACzBC,cAAcI,aAAaL,WAC3BG,aAAaC,WAAWC;AAE5B;AAEA,wEAAwE,GACxE,SAASM,sBAAsB9B,KAAa,EAAE+B,cAA8B;IAC1E,MAAMP,cAAczB,kBAAkBC;IAEtC,IAAI,CAACwB,YAAYZ,SAAS,EAAE;QAC1B,OAAOmB,eAAeC,IAAI,CAAC,CAACX,UAC1BQ,sBAAsBR,SAASG,aAAaA,YAAYN,SAAS;IAErE;IAEA,IAAIe,yBAAyBC;IAC7B,KAAK,MAAMb,WAAWU,eAAgB;QACpC,IAAIV,QAAQT,SAAS,IAAIU,aAAaD,SAASG,cAAc;YAC3DS,yBAAyBE,KAAKC,GAAG,CAC/BH,wBACAE,KAAKE,GAAG,CAACb,YAAYN,SAAS,EAAEG,QAAQH,SAAS;QAErD;IACF;IAEA,IAAIe,2BAA2BC,UAAU,OAAO;IAEhD,yEAAyE;IACzE,wEAAwE;IACxE,IACE,IAAIf,SAASK,YAAYN,SAAS,EAClCC,SAASc,wBACTd,SACA;QACA,IACE,CAACY,eAAeC,IAAI,CAAC,CAACX,UACpBQ,sBAAsBR,SAASG,aAAaL,UAE9C;YACA,OAAO;QACT;IACF;IAEA,OAAO;AACT;AAEO,SAASrB,2BAA2BwC,IAAY;IACrD,wCAAwC;IACxC,OACEA,KACGpC,KAAK,CAAC,KACNqC,IAAI,CAAC,CAACtB,UACLtB,2BAA2B4C,IAAI,CAAC,CAACC,IAAMvB,QAAQR,UAAU,CAAC+B,SACtDhC;AAEZ;AAiBO,SAASZ,oCACd0C,IAAY;IAEZ,IAAIG;IACJ,IAAIC;IACJ,IAAIC;IAEJ,KAAK,MAAM1B,WAAWqB,KAAKpC,KAAK,CAAC,KAAM;QACrCwC,SAAS/C,2BAA2B4C,IAAI,CAAC,CAACC,IAAMvB,QAAQR,UAAU,CAAC+B;QACnE,IAAIE,QAAQ;;YACT,CAACD,mBAAmBE,iBAAiB,GAAGL,KAAKpC,KAAK,CAACwC,QAAQ;YAC5D;QACF;IACF;IAEA,IAAI,CAACD,qBAAqB,CAACC,UAAU,CAACC,kBAAkB;QACtD,MAAM,IAAIC,MACR,CAAC,4BAA4B,EAAEN,KAAK,iFAAiF,CAAC;IAE1H;IAEAG,oBAAoBI,IAAAA,0BAAgB,EAACJ,mBAAmB,iDAAiD;;IAEzG,OAAQC;QACN,KAAK;YACH,oIAAoI;YACpI,IAAID,sBAAsB,KAAK;gBAC7BE,mBAAmB,CAAC,CAAC,EAAEA,kBAAkB;YAC3C,OAAO;gBACLA,mBAAmBF,oBAAoB,MAAME;YAC/C;YACA;QACF,KAAK;YACH,uHAAuH;YACvH,IAAIF,sBAAsB,KAAK;gBAC7B,MAAM,IAAIG,MACR,CAAC,4BAA4B,EAAEN,KAAK,4DAA4D,CAAC;YAErG;YACAK,mBAAmBF,kBAChBvC,KAAK,CAAC,KACNY,KAAK,CAAC,GAAG,CAAC,GACVgC,MAAM,CAACH,kBACPI,IAAI,CAAC;YACR;QACF,KAAK;YACH,kIAAkI;YAClIJ,mBAAmB,MAAMA;YACzB;QACF,KAAK;YACH,iIAAiI;YAEjI,MAAMK,yBAAyBP,kBAAkBvC,KAAK,CAAC;YACvD,IAAI8C,uBAAuB7B,MAAM,IAAI,GAAG;gBACtC,MAAM,IAAIyB,MACR,CAAC,4BAA4B,EAAEN,KAAK,+DAA+D,CAAC;YAExG;YAEAK,mBAAmBK,uBAChBlC,KAAK,CAAC,GAAG,CAAC,GACVgC,MAAM,CAACH,kBACPI,IAAI,CAAC;YACR;QACF;YACE,MAAM,IAAIH,MAAM;IACpB;IAEA,OAAO;QAAEH;QAAmBE;IAAiB;AAC/C;AAQO,SAAS9C,uCACdoD,QAAkC;IAElC,MAAMC,kBAAkBC,OAAOC,IAAI,CAACH,UAAU9C,MAAM,CAClD,CAACH,QAAU,CAACF,2BAA2BE;IAEzC,MAAMqD,yBAAyBH,gBAAgBlC,GAAG,CAACjB;IAEnD,OAAOoD,OAAOC,IAAI,CAACH,UAChB9C,MAAM,CAACL,4BACPkB,GAAG,CAAC,CAACsC,oBAAuB,CAAA;YAC3BA;YACAC,gBACE3D,oCAAoC0D,mBAAmBX,gBAAgB;QAC3E,CAAA,GACCxC,MAAM,CACL,CAAC,EAAEoD,cAAc,EAAE,GACjB,CAACzB,sBAAsByB,gBAAgBF,yBAE1CG,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEH,iBAAiB,CAACK,aAAa,CAACD,EAAEJ,iBAAiB;AACzE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..107890443ab9c2b24497ec70e3342ebfdf54cdb8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.d.ts @@ -0,0 +1,5 @@ +import type { ParsedUrlQuery } from 'querystring'; +export declare function interpolateAs(route: string, asPathname: string, query: ParsedUrlQuery): { + params: string[]; + result: string; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.js new file mode 100644 index 0000000000000000000000000000000000000000..1bf6dc9f3a6041a1ec3f81fc2c0e24188b986fba --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "interpolateAs", { + enumerable: true, + get: function() { + return interpolateAs; + } +}); +const _routematcher = require("./route-matcher"); +const _routeregex = require("./route-regex"); +function interpolateAs(route, asPathname, query) { + let interpolatedRoute = ''; + const dynamicRegex = (0, _routeregex.getRouteRegex)(route); + const dynamicGroups = dynamicRegex.groups; + const dynamicMatches = // Try to match the dynamic route against the asPath + (asPathname !== route ? (0, _routematcher.getRouteMatcher)(dynamicRegex)(asPathname) : '') || // Fall back to reading the values from the href + // TODO: should this take priority; also need to change in the router. + query; + interpolatedRoute = route; + const params = Object.keys(dynamicGroups); + if (!params.every((param)=>{ + let value = dynamicMatches[param] || ''; + const { repeat, optional } = dynamicGroups[param]; + // support single-level catch-all + // TODO: more robust handling for user-error (passing `/`) + let replaced = `[${repeat ? '...' : ''}${param}]`; + if (optional) { + replaced = `${!value ? '/' : ''}[${replaced}]`; + } + if (repeat && !Array.isArray(value)) value = [ + value + ]; + return (optional || param in dynamicMatches) && // Interpolate group into data URL if present + (interpolatedRoute = interpolatedRoute.replace(replaced, repeat ? value.map(// these values should be fully encoded instead of just + // path delimiter escaped since they are being inserted + // into the URL and we expect URL encoded segments + // when parsing dynamic route params + (segment)=>encodeURIComponent(segment)).join('/') : encodeURIComponent(value)) || '/'); + })) { + interpolatedRoute = '' // did not satisfy all requirements + ; + // n.b. We ignore this error because we handle warning for this case in + // development in the `` component directly. + } + return { + params, + result: interpolatedRoute + }; +} + +//# sourceMappingURL=interpolate-as.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eb9b972b3726cb426786b1882cd67f912cda1281 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/interpolate-as.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/interpolate-as.ts"],"sourcesContent":["import type { ParsedUrlQuery } from 'querystring'\n\nimport { getRouteMatcher } from './route-matcher'\nimport { getRouteRegex } from './route-regex'\n\nexport function interpolateAs(\n route: string,\n asPathname: string,\n query: ParsedUrlQuery\n) {\n let interpolatedRoute = ''\n\n const dynamicRegex = getRouteRegex(route)\n const dynamicGroups = dynamicRegex.groups\n const dynamicMatches =\n // Try to match the dynamic route against the asPath\n (asPathname !== route ? getRouteMatcher(dynamicRegex)(asPathname) : '') ||\n // Fall back to reading the values from the href\n // TODO: should this take priority; also need to change in the router.\n query\n\n interpolatedRoute = route\n const params = Object.keys(dynamicGroups)\n\n if (\n !params.every((param) => {\n let value = dynamicMatches[param] || ''\n const { repeat, optional } = dynamicGroups[param]\n\n // support single-level catch-all\n // TODO: more robust handling for user-error (passing `/`)\n let replaced = `[${repeat ? '...' : ''}${param}]`\n if (optional) {\n replaced = `${!value ? '/' : ''}[${replaced}]`\n }\n if (repeat && !Array.isArray(value)) value = [value]\n\n return (\n (optional || param in dynamicMatches) &&\n // Interpolate group into data URL if present\n (interpolatedRoute =\n interpolatedRoute!.replace(\n replaced,\n repeat\n ? (value as string[])\n .map(\n // these values should be fully encoded instead of just\n // path delimiter escaped since they are being inserted\n // into the URL and we expect URL encoded segments\n // when parsing dynamic route params\n (segment) => encodeURIComponent(segment)\n )\n .join('/')\n : encodeURIComponent(value as string)\n ) || '/')\n )\n })\n ) {\n interpolatedRoute = '' // did not satisfy all requirements\n\n // n.b. We ignore this error because we handle warning for this case in\n // development in the `` component directly.\n }\n return {\n params,\n result: interpolatedRoute,\n }\n}\n"],"names":["interpolateAs","route","asPathname","query","interpolatedRoute","dynamicRegex","getRouteRegex","dynamicGroups","groups","dynamicMatches","getRouteMatcher","params","Object","keys","every","param","value","repeat","optional","replaced","Array","isArray","replace","map","segment","encodeURIComponent","join","result"],"mappings":";;;;+BAKgBA;;;eAAAA;;;8BAHgB;4BACF;AAEvB,SAASA,cACdC,KAAa,EACbC,UAAkB,EAClBC,KAAqB;IAErB,IAAIC,oBAAoB;IAExB,MAAMC,eAAeC,IAAAA,yBAAa,EAACL;IACnC,MAAMM,gBAAgBF,aAAaG,MAAM;IACzC,MAAMC,iBAEJ,AADA,oDAAoD;IACnDP,CAAAA,eAAeD,QAAQS,IAAAA,6BAAe,EAACL,cAAcH,cAAc,EAAC,KACrE,gDAAgD;IAChD,sEAAsE;IACtEC;IAEFC,oBAAoBH;IACpB,MAAMU,SAASC,OAAOC,IAAI,CAACN;IAE3B,IACE,CAACI,OAAOG,KAAK,CAAC,CAACC;QACb,IAAIC,QAAQP,cAAc,CAACM,MAAM,IAAI;QACrC,MAAM,EAAEE,MAAM,EAAEC,QAAQ,EAAE,GAAGX,aAAa,CAACQ,MAAM;QAEjD,iCAAiC;QACjC,0DAA0D;QAC1D,IAAII,WAAW,CAAC,CAAC,EAAEF,SAAS,QAAQ,KAAKF,MAAM,CAAC,CAAC;QACjD,IAAIG,UAAU;YACZC,WAAW,GAAG,CAACH,QAAQ,MAAM,GAAG,CAAC,EAAEG,SAAS,CAAC,CAAC;QAChD;QACA,IAAIF,UAAU,CAACG,MAAMC,OAAO,CAACL,QAAQA,QAAQ;YAACA;SAAM;QAEpD,OACE,AAACE,CAAAA,YAAYH,SAASN,cAAa,KACnC,6CAA6C;QAC5CL,CAAAA,oBACCA,kBAAmBkB,OAAO,CACxBH,UACAF,SACI,AAACD,MACEO,GAAG,CACF,uDAAuD;QACvD,uDAAuD;QACvD,kDAAkD;QAClD,oCAAoC;QACpC,CAACC,UAAYC,mBAAmBD,UAEjCE,IAAI,CAAC,OACRD,mBAAmBT,WACpB,GAAE;IAEb,IACA;QACAZ,oBAAoB,GAAG,mCAAmC;;IAE1D,uEAAuE;IACvE,kDAAkD;IACpD;IACA,OAAO;QACLO;QACAgB,QAAQvB;IACV;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ad4054ecb9070ecff83271f77afa86e36af7ee0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.d.ts @@ -0,0 +1,5 @@ +import { HTML_LIMITED_BOT_UA_RE } from './html-bots'; +export declare const HTML_LIMITED_BOT_UA_RE_STRING: string; +export { HTML_LIMITED_BOT_UA_RE }; +export declare function isBot(userAgent: string): boolean; +export declare function getBotType(userAgent: string): 'dom' | 'html' | undefined; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.js new file mode 100644 index 0000000000000000000000000000000000000000..309bb78d706b82aadc5cea1cce85b54b859ff6f2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + HTML_LIMITED_BOT_UA_RE: null, + HTML_LIMITED_BOT_UA_RE_STRING: null, + getBotType: null, + isBot: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + HTML_LIMITED_BOT_UA_RE: function() { + return _htmlbots.HTML_LIMITED_BOT_UA_RE; + }, + HTML_LIMITED_BOT_UA_RE_STRING: function() { + return HTML_LIMITED_BOT_UA_RE_STRING; + }, + getBotType: function() { + return getBotType; + }, + isBot: function() { + return isBot; + } +}); +const _htmlbots = require("./html-bots"); +// Bot crawler that will spin up a headless browser and execute JS. +// Only the main Googlebot search crawler executes JavaScript, not other Google crawlers. +// x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers +// This regex specifically matches "Googlebot" but NOT "Mediapartners-Google", "AdsBot-Google", etc. +const HEADLESS_BROWSER_BOT_UA_RE = /Googlebot(?!-)|Googlebot$/i; +const HTML_LIMITED_BOT_UA_RE_STRING = _htmlbots.HTML_LIMITED_BOT_UA_RE.source; +function isDomBotUA(userAgent) { + return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent); +} +function isHtmlLimitedBotUA(userAgent) { + return _htmlbots.HTML_LIMITED_BOT_UA_RE.test(userAgent); +} +function isBot(userAgent) { + return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent); +} +function getBotType(userAgent) { + if (isDomBotUA(userAgent)) { + return 'dom'; + } + if (isHtmlLimitedBotUA(userAgent)) { + return 'html'; + } + return undefined; +} + +//# sourceMappingURL=is-bot.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.js.map new file mode 100644 index 0000000000000000000000000000000000000000..181b58dee332df01f2e86233f0ccac78fe5b2a5d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-bot.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/is-bot.ts"],"sourcesContent":["import { HTML_LIMITED_BOT_UA_RE } from './html-bots'\n\n// Bot crawler that will spin up a headless browser and execute JS.\n// Only the main Googlebot search crawler executes JavaScript, not other Google crawlers.\n// x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers\n// This regex specifically matches \"Googlebot\" but NOT \"Mediapartners-Google\", \"AdsBot-Google\", etc.\nconst HEADLESS_BROWSER_BOT_UA_RE = /Googlebot(?!-)|Googlebot$/i\n\nexport const HTML_LIMITED_BOT_UA_RE_STRING = HTML_LIMITED_BOT_UA_RE.source\n\nexport { HTML_LIMITED_BOT_UA_RE }\n\nfunction isDomBotUA(userAgent: string) {\n return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent)\n}\n\nfunction isHtmlLimitedBotUA(userAgent: string) {\n return HTML_LIMITED_BOT_UA_RE.test(userAgent)\n}\n\nexport function isBot(userAgent: string): boolean {\n return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent)\n}\n\nexport function getBotType(userAgent: string): 'dom' | 'html' | undefined {\n if (isDomBotUA(userAgent)) {\n return 'dom'\n }\n if (isHtmlLimitedBotUA(userAgent)) {\n return 'html'\n }\n return undefined\n}\n"],"names":["HTML_LIMITED_BOT_UA_RE","HTML_LIMITED_BOT_UA_RE_STRING","getBotType","isBot","HEADLESS_BROWSER_BOT_UA_RE","source","isDomBotUA","userAgent","test","isHtmlLimitedBotUA","undefined"],"mappings":";;;;;;;;;;;;;;;;;IAUSA,sBAAsB;eAAtBA,gCAAsB;;IAFlBC,6BAA6B;eAA7BA;;IAgBGC,UAAU;eAAVA;;IAJAC,KAAK;eAALA;;;0BApBuB;AAEvC,mEAAmE;AACnE,yFAAyF;AACzF,4FAA4F;AAC5F,oGAAoG;AACpG,MAAMC,6BAA6B;AAE5B,MAAMH,gCAAgCD,gCAAsB,CAACK,MAAM;AAI1E,SAASC,WAAWC,SAAiB;IACnC,OAAOH,2BAA2BI,IAAI,CAACD;AACzC;AAEA,SAASE,mBAAmBF,SAAiB;IAC3C,OAAOP,gCAAsB,CAACQ,IAAI,CAACD;AACrC;AAEO,SAASJ,MAAMI,SAAiB;IACrC,OAAOD,WAAWC,cAAcE,mBAAmBF;AACrD;AAEO,SAASL,WAAWK,SAAiB;IAC1C,IAAID,WAAWC,YAAY;QACzB,OAAO;IACT;IACA,IAAIE,mBAAmBF,YAAY;QACjC,OAAO;IACT;IACA,OAAOG;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7baf0ff695e75be75ef6e09c9039eefeb67450b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.d.ts @@ -0,0 +1,8 @@ +/** + * Check if a route is dynamic. + * + * @param route - The route to check. + * @param strict - Whether to use strict mode which prohibits segments with prefixes/suffixes (default: true). + * @returns Whether the route is dynamic. + */ +export declare function isDynamicRoute(route: string, strict?: boolean): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..77effe896657a4ec9f7789f051a2bf700a1001f7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isDynamicRoute", { + enumerable: true, + get: function() { + return isDynamicRoute; + } +}); +const _interceptionroutes = require("./interception-routes"); +// Identify /.*[param].*/ in route string +const TEST_ROUTE = /\/[^/]*\[[^/]+\][^/]*(?=\/|$)/; +// Identify /[param]/ in route string +const TEST_STRICT_ROUTE = /\/\[[^/]+\](?=\/|$)/; +function isDynamicRoute(route, strict = true) { + if ((0, _interceptionroutes.isInterceptionRouteAppPath)(route)) { + route = (0, _interceptionroutes.extractInterceptionRouteInformation)(route).interceptedRoute; + } + if (strict) { + return TEST_STRICT_ROUTE.test(route); + } + return TEST_ROUTE.test(route); +} + +//# sourceMappingURL=is-dynamic.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bfde3a1b4d31b1d73a8ae7641491c0a295dc1d19 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-dynamic.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/is-dynamic.ts"],"sourcesContent":["import {\n extractInterceptionRouteInformation,\n isInterceptionRouteAppPath,\n} from './interception-routes'\n\n// Identify /.*[param].*/ in route string\nconst TEST_ROUTE = /\\/[^/]*\\[[^/]+\\][^/]*(?=\\/|$)/\n\n// Identify /[param]/ in route string\nconst TEST_STRICT_ROUTE = /\\/\\[[^/]+\\](?=\\/|$)/\n\n/**\n * Check if a route is dynamic.\n *\n * @param route - The route to check.\n * @param strict - Whether to use strict mode which prohibits segments with prefixes/suffixes (default: true).\n * @returns Whether the route is dynamic.\n */\nexport function isDynamicRoute(route: string, strict: boolean = true): boolean {\n if (isInterceptionRouteAppPath(route)) {\n route = extractInterceptionRouteInformation(route).interceptedRoute\n }\n\n if (strict) {\n return TEST_STRICT_ROUTE.test(route)\n }\n\n return TEST_ROUTE.test(route)\n}\n"],"names":["isDynamicRoute","TEST_ROUTE","TEST_STRICT_ROUTE","route","strict","isInterceptionRouteAppPath","extractInterceptionRouteInformation","interceptedRoute","test"],"mappings":";;;;+BAkBgBA;;;eAAAA;;;oCAfT;AAEP,yCAAyC;AACzC,MAAMC,aAAa;AAEnB,qCAAqC;AACrC,MAAMC,oBAAoB;AASnB,SAASF,eAAeG,KAAa,EAAEC,SAAkB,IAAI;IAClE,IAAIC,IAAAA,8CAA0B,EAACF,QAAQ;QACrCA,QAAQG,IAAAA,uDAAmC,EAACH,OAAOI,gBAAgB;IACrE;IAEA,IAAIH,QAAQ;QACV,OAAOF,kBAAkBM,IAAI,CAACL;IAChC;IAEA,OAAOF,WAAWO,IAAI,CAACL;AACzB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe2ceecca90495590f44b2cfe146ae0811c97003 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.d.ts @@ -0,0 +1,4 @@ +/** + * Detects whether a given url is routable by the Next.js router (browser only). + */ +export declare function isLocalURL(url: string): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.js new file mode 100644 index 0000000000000000000000000000000000000000..48a4d677c578396c3bdd9d5132acf7b0578009b2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isLocalURL", { + enumerable: true, + get: function() { + return isLocalURL; + } +}); +const _utils = require("../../utils"); +const _hasbasepath = require("../../../../client/has-base-path"); +function isLocalURL(url) { + // prevent a hydration mismatch on href for url with anchor refs + if (!(0, _utils.isAbsoluteUrl)(url)) return true; + try { + // absolute urls can be local if they are on the same origin + const locationOrigin = (0, _utils.getLocationOrigin)(); + const resolved = new URL(url, locationOrigin); + return resolved.origin === locationOrigin && (0, _hasbasepath.hasBasePath)(resolved.pathname); + } catch (_) { + return false; + } +} + +//# sourceMappingURL=is-local-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5aef535ee74495369faabd6730d2e2fe3f83409b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/is-local-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/is-local-url.ts"],"sourcesContent":["import { isAbsoluteUrl, getLocationOrigin } from '../../utils'\nimport { hasBasePath } from '../../../../client/has-base-path'\n\n/**\n * Detects whether a given url is routable by the Next.js router (browser only).\n */\nexport function isLocalURL(url: string): boolean {\n // prevent a hydration mismatch on href for url with anchor refs\n if (!isAbsoluteUrl(url)) return true\n try {\n // absolute urls can be local if they are on the same origin\n const locationOrigin = getLocationOrigin()\n const resolved = new URL(url, locationOrigin)\n return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)\n } catch (_) {\n return false\n }\n}\n"],"names":["isLocalURL","url","isAbsoluteUrl","locationOrigin","getLocationOrigin","resolved","URL","origin","hasBasePath","pathname","_"],"mappings":";;;;+BAMgBA;;;eAAAA;;;uBANiC;6BACrB;AAKrB,SAASA,WAAWC,GAAW;IACpC,gEAAgE;IAChE,IAAI,CAACC,IAAAA,oBAAa,EAACD,MAAM,OAAO;IAChC,IAAI;QACF,4DAA4D;QAC5D,MAAME,iBAAiBC,IAAAA,wBAAiB;QACxC,MAAMC,WAAW,IAAIC,IAAIL,KAAKE;QAC9B,OAAOE,SAASE,MAAM,KAAKJ,kBAAkBK,IAAAA,wBAAW,EAACH,SAASI,QAAQ;IAC5E,EAAE,OAAOC,GAAG;QACV,OAAO;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4c97d95a83d8b09509d9fad298be825fc702170 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.d.ts @@ -0,0 +1,7 @@ +import type { BaseNextRequest } from '../../../../server/base-http'; +import type { ProxyMatcher } from '../../../../build/analysis/get-page-static-info'; +import type { Params } from '../../../../server/request/params'; +export interface MiddlewareRouteMatch { + (pathname: string | null | undefined, request: BaseNextRequest, query: Params): boolean; +} +export declare function getMiddlewareRouteMatcher(matchers: ProxyMatcher[]): MiddlewareRouteMatch; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js new file mode 100644 index 0000000000000000000000000000000000000000..285f4d2bb8ca915380c7404f6a488335c7b9abb4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getMiddlewareRouteMatcher", { + enumerable: true, + get: function() { + return getMiddlewareRouteMatcher; + } +}); +const _preparedestination = require("./prepare-destination"); +function getMiddlewareRouteMatcher(matchers) { + return (pathname, req, query)=>{ + for (const matcher of matchers){ + const routeMatch = new RegExp(matcher.regexp).exec(pathname); + if (!routeMatch) { + continue; + } + if (matcher.has || matcher.missing) { + const hasParams = (0, _preparedestination.matchHas)(req, query, matcher.has, matcher.missing); + if (!hasParams) { + continue; + } + } + return true; + } + return false; + }; +} + +//# sourceMappingURL=middleware-route-matcher.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7364b7e646b2dc3274557ed8386fa90a142e172d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/middleware-route-matcher.ts"],"sourcesContent":["import type { BaseNextRequest } from '../../../../server/base-http'\nimport type { ProxyMatcher } from '../../../../build/analysis/get-page-static-info'\nimport type { Params } from '../../../../server/request/params'\nimport { matchHas } from './prepare-destination'\n\nexport interface MiddlewareRouteMatch {\n (\n pathname: string | null | undefined,\n request: BaseNextRequest,\n query: Params\n ): boolean\n}\n\nexport function getMiddlewareRouteMatcher(\n matchers: ProxyMatcher[]\n): MiddlewareRouteMatch {\n return (\n pathname: string | null | undefined,\n req: BaseNextRequest,\n query: Params\n ) => {\n for (const matcher of matchers) {\n const routeMatch = new RegExp(matcher.regexp).exec(pathname!)\n if (!routeMatch) {\n continue\n }\n\n if (matcher.has || matcher.missing) {\n const hasParams = matchHas(req, query, matcher.has, matcher.missing)\n if (!hasParams) {\n continue\n }\n }\n\n return true\n }\n\n return false\n }\n}\n"],"names":["getMiddlewareRouteMatcher","matchers","pathname","req","query","matcher","routeMatch","RegExp","regexp","exec","has","missing","hasParams","matchHas"],"mappings":";;;;+BAagBA;;;eAAAA;;;oCAVS;AAUlB,SAASA,0BACdC,QAAwB;IAExB,OAAO,CACLC,UACAC,KACAC;QAEA,KAAK,MAAMC,WAAWJ,SAAU;YAC9B,MAAMK,aAAa,IAAIC,OAAOF,QAAQG,MAAM,EAAEC,IAAI,CAACP;YACnD,IAAI,CAACI,YAAY;gBACf;YACF;YAEA,IAAID,QAAQK,GAAG,IAAIL,QAAQM,OAAO,EAAE;gBAClC,MAAMC,YAAYC,IAAAA,4BAAQ,EAACV,KAAKC,OAAOC,QAAQK,GAAG,EAAEL,QAAQM,OAAO;gBACnE,IAAI,CAACC,WAAW;oBACd;gBACF;YACF;YAEA,OAAO;QACT;QAEA,OAAO;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..24425e58a78b47f5d737210491d21f8a00e1062c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.d.ts @@ -0,0 +1,3 @@ +export declare function omit(object: T, keys: K[]): Omit; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.js new file mode 100644 index 0000000000000000000000000000000000000000..7b2bc1c0d194b5d65713f9bb833d3d99c42a4713 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "omit", { + enumerable: true, + get: function() { + return omit; + } +}); +function omit(object, keys) { + const omitted = {}; + Object.keys(object).forEach((key)=>{ + if (!keys.includes(key)) { + omitted[key] = object[key]; + } + }); + return omitted; +} + +//# sourceMappingURL=omit.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.js.map new file mode 100644 index 0000000000000000000000000000000000000000..472610dab7b5e51b439a4f99ff0698d805c77c4e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/omit.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/omit.ts"],"sourcesContent":["export function omit(\n object: T,\n keys: K[]\n): Omit {\n const omitted: { [key: string]: unknown } = {}\n Object.keys(object).forEach((key) => {\n if (!keys.includes(key as K)) {\n omitted[key] = object[key]\n }\n })\n return omitted as Omit\n}\n"],"names":["omit","object","keys","omitted","Object","forEach","key","includes"],"mappings":";;;;+BAAgBA;;;eAAAA;;;AAAT,SAASA,KACdC,MAAS,EACTC,IAAS;IAET,MAAMC,UAAsC,CAAC;IAC7CC,OAAOF,IAAI,CAACD,QAAQI,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACJ,KAAKK,QAAQ,CAACD,MAAW;YAC5BH,OAAO,CAACG,IAAI,GAAGL,MAAM,CAACK,IAAI;QAC5B;IACF;IACA,OAAOH;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57dbbad9087705a7743218def8340d3d2f6fc412 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.d.ts @@ -0,0 +1,11 @@ +import type { LoaderTree } from '../../../../server/lib/app-dir-module'; +export declare function parseLoaderTree(tree: LoaderTree): { + page: import("../../../../build/webpack/loaders/metadata/types").ModuleTuple | undefined; + segment: string; + modules: import("../../../../build/webpack/loaders/next-app-loader").AppDirModules; + conventionPath: string | undefined; + parallelRoutes: { + [parallelRouterKey: string]: LoaderTree; + }; + staticSiblings: readonly string[] | null; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.js new file mode 100644 index 0000000000000000000000000000000000000000..59305025601b558981ee7d3446adf529bd6e7f40 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "parseLoaderTree", { + enumerable: true, + get: function() { + return parseLoaderTree; + } +}); +const _segment = require("../../segment"); +function parseLoaderTree(tree) { + const [segment, parallelRoutes, modules, staticSiblings] = tree; + const { layout, template } = modules; + let { page } = modules; + // a __DEFAULT__ segment means that this route didn't match any of the + // segments in the route, so we should use the default page + page = segment === _segment.DEFAULT_SEGMENT_KEY ? modules.defaultPage : page; + const conventionPath = layout?.[1] || template?.[1] || page?.[1]; + return { + page, + segment, + modules, + /* it can be either layout / template / page */ conventionPath, + parallelRoutes, + staticSiblings + }; +} + +//# sourceMappingURL=parse-loader-tree.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.js.map new file mode 100644 index 0000000000000000000000000000000000000000..371b571ba0132fc2b10b89db206c3d2a05896b50 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/parse-loader-tree.ts"],"sourcesContent":["import { DEFAULT_SEGMENT_KEY } from '../../segment'\nimport type { LoaderTree } from '../../../../server/lib/app-dir-module'\n\nexport function parseLoaderTree(tree: LoaderTree) {\n const [segment, parallelRoutes, modules, staticSiblings] = tree\n const { layout, template } = modules\n let { page } = modules\n // a __DEFAULT__ segment means that this route didn't match any of the\n // segments in the route, so we should use the default page\n page = segment === DEFAULT_SEGMENT_KEY ? modules.defaultPage : page\n\n const conventionPath = layout?.[1] || template?.[1] || page?.[1]\n\n return {\n page,\n segment,\n modules,\n /* it can be either layout / template / page */\n conventionPath,\n parallelRoutes,\n staticSiblings,\n }\n}\n"],"names":["parseLoaderTree","tree","segment","parallelRoutes","modules","staticSiblings","layout","template","page","DEFAULT_SEGMENT_KEY","defaultPage","conventionPath"],"mappings":";;;;+BAGgBA;;;eAAAA;;;yBAHoB;AAG7B,SAASA,gBAAgBC,IAAgB;IAC9C,MAAM,CAACC,SAASC,gBAAgBC,SAASC,eAAe,GAAGJ;IAC3D,MAAM,EAAEK,MAAM,EAAEC,QAAQ,EAAE,GAAGH;IAC7B,IAAI,EAAEI,IAAI,EAAE,GAAGJ;IACf,sEAAsE;IACtE,2DAA2D;IAC3DI,OAAON,YAAYO,4BAAmB,GAAGL,QAAQM,WAAW,GAAGF;IAE/D,MAAMG,iBAAiBL,QAAQ,CAAC,EAAE,IAAIC,UAAU,CAAC,EAAE,IAAIC,MAAM,CAAC,EAAE;IAEhE,OAAO;QACLA;QACAN;QACAE;QACA,6CAA6C,GAC7CO;QACAR;QACAE;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ed036004a43ead40df1316cb146e147c99533a4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.d.ts @@ -0,0 +1,10 @@ +/** + * Given a path this function will find the pathname, query and hash and return + * them. This is useful to parse full paths on the client side. + * @param path A path to parse e.g. /foo/bar?id=1#hash + */ +export declare function parsePath(path: string): { + pathname: string; + query: string; + hash: string; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.js new file mode 100644 index 0000000000000000000000000000000000000000..f8230d414c379dd853df72b7a6659f41be13925c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.js @@ -0,0 +1,33 @@ +/** + * Given a path this function will find the pathname, query and hash and return + * them. This is useful to parse full paths on the client side. + * @param path A path to parse e.g. /foo/bar?id=1#hash + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "parsePath", { + enumerable: true, + get: function() { + return parsePath; + } +}); +function parsePath(path) { + const hashIndex = path.indexOf('#'); + const queryIndex = path.indexOf('?'); + const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex); + if (hasQuery || hashIndex > -1) { + return { + pathname: path.substring(0, hasQuery ? queryIndex : hashIndex), + query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : '', + hash: hashIndex > -1 ? path.slice(hashIndex) : '' + }; + } + return { + pathname: path, + query: '', + hash: '' + }; +} + +//# sourceMappingURL=parse-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..54a014c195694a7b766fb8bd9c9ed901a3417169 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/parse-path.ts"],"sourcesContent":["/**\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nexport function parsePath(path: string) {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery\n ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined)\n : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return { pathname: path, query: '', hash: '' }\n}\n"],"names":["parsePath","path","hashIndex","indexOf","queryIndex","hasQuery","pathname","substring","query","undefined","hash","slice"],"mappings":"AAAA;;;;CAIC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,UAAUC,IAAY;IACpC,MAAMC,YAAYD,KAAKE,OAAO,CAAC;IAC/B,MAAMC,aAAaH,KAAKE,OAAO,CAAC;IAChC,MAAME,WAAWD,aAAa,CAAC,KAAMF,CAAAA,YAAY,KAAKE,aAAaF,SAAQ;IAE3E,IAAIG,YAAYH,YAAY,CAAC,GAAG;QAC9B,OAAO;YACLI,UAAUL,KAAKM,SAAS,CAAC,GAAGF,WAAWD,aAAaF;YACpDM,OAAOH,WACHJ,KAAKM,SAAS,CAACH,YAAYF,YAAY,CAAC,IAAIA,YAAYO,aACxD;YACJC,MAAMR,YAAY,CAAC,IAAID,KAAKU,KAAK,CAACT,aAAa;QACjD;IACF;IAEA,OAAO;QAAEI,UAAUL;QAAMO,OAAO;QAAIE,MAAM;IAAG;AAC/C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c942b0df1d2356ac78c27a2c600339b4222de9a9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.d.ts @@ -0,0 +1,22 @@ +import type { ParsedUrlQuery } from 'querystring'; +export interface ParsedRelativeUrl { + auth: string | null; + hash: string; + host: string | null; + hostname: string | null; + href: string; + pathname: string; + port: string | null; + protocol: string | null; + query: ParsedUrlQuery; + search: string; + slashes: null; +} +/** + * Parses path-relative urls (e.g. `/hello/world?foo=bar`). If url isn't path-relative + * (e.g. `./hello`) then at least base must be. + * Absolute urls are rejected with one exception, in the browser, absolute urls that are on + * the current origin will be parsed as relative + */ +export declare function parseRelativeUrl(url: string, base?: string, parseQuery?: true): ParsedRelativeUrl; +export declare function parseRelativeUrl(url: string, base: string | undefined, parseQuery: false): Omit; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js new file mode 100644 index 0000000000000000000000000000000000000000..40e6f38df5f27cb3503f461712280df7810c9bfd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "parseRelativeUrl", { + enumerable: true, + get: function() { + return parseRelativeUrl; + } +}); +const _utils = require("../../utils"); +const _querystring = require("./querystring"); +function parseRelativeUrl(url, base, parseQuery = true) { + const globalBase = new URL(typeof window === 'undefined' ? 'http://n' : (0, _utils.getLocationOrigin)()); + const resolvedBase = base ? new URL(base, globalBase) : url.startsWith('.') ? new URL(typeof window === 'undefined' ? 'http://n' : window.location.href) : globalBase; + const { pathname, searchParams, search, hash, href, origin } = url.startsWith('/') ? // See https://nodejs.org/api/http.html#messageurl + // Not using `origin` to support other protocols + new URL(`${resolvedBase.protocol}//${resolvedBase.host}${url}`) : new URL(url, resolvedBase); + if (origin !== globalBase.origin) { + throw new Error(`invariant: invalid relative URL, router received ${url}`); + } + return { + auth: null, + host: null, + hostname: null, + pathname, + port: null, + protocol: null, + query: parseQuery ? (0, _querystring.searchParamsToUrlQuery)(searchParams) : undefined, + search, + hash, + href: href.slice(origin.length), + // We don't know for relative URLs at this point since we set a custom, internal + // base that isn't surfaced to users. + slashes: null + }; +} + +//# sourceMappingURL=parse-relative-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dfb7af69bba2ca8020743122b5eb1d8d2048cc8e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/parse-relative-url.ts"],"sourcesContent":["import type { ParsedUrlQuery } from 'querystring'\nimport { getLocationOrigin } from '../../utils'\nimport { searchParamsToUrlQuery } from './querystring'\n\nexport interface ParsedRelativeUrl {\n auth: string | null\n hash: string\n host: string | null\n hostname: string | null\n href: string\n pathname: string\n port: string | null\n protocol: string | null\n query: ParsedUrlQuery\n search: string\n slashes: null\n}\n\n/**\n * Parses path-relative urls (e.g. `/hello/world?foo=bar`). If url isn't path-relative\n * (e.g. `./hello`) then at least base must be.\n * Absolute urls are rejected with one exception, in the browser, absolute urls that are on\n * the current origin will be parsed as relative\n */\nexport function parseRelativeUrl(\n url: string,\n base?: string,\n parseQuery?: true\n): ParsedRelativeUrl\nexport function parseRelativeUrl(\n url: string,\n base: string | undefined,\n parseQuery: false\n): Omit\nexport function parseRelativeUrl(\n url: string,\n base?: string,\n parseQuery = true\n): ParsedRelativeUrl | Omit {\n const globalBase = new URL(\n typeof window === 'undefined' ? 'http://n' : getLocationOrigin()\n )\n\n const resolvedBase = base\n ? new URL(base, globalBase)\n : url.startsWith('.')\n ? new URL(\n typeof window === 'undefined' ? 'http://n' : window.location.href\n )\n : globalBase\n\n const { pathname, searchParams, search, hash, href, origin } = url.startsWith(\n '/'\n )\n ? // 'http://localhost:3000///' would be received as '///' in Node.js' IncomingMessage\n // See https://nodejs.org/api/http.html#messageurl\n // Not using `origin` to support other protocols\n new URL(`${resolvedBase.protocol}//${resolvedBase.host}${url}`)\n : new URL(url, resolvedBase)\n\n if (origin !== globalBase.origin) {\n throw new Error(`invariant: invalid relative URL, router received ${url}`)\n }\n\n return {\n auth: null,\n host: null,\n hostname: null,\n pathname,\n port: null,\n protocol: null,\n query: parseQuery ? searchParamsToUrlQuery(searchParams) : undefined,\n search,\n hash,\n href: href.slice(origin.length),\n // We don't know for relative URLs at this point since we set a custom, internal\n // base that isn't surfaced to users.\n slashes: null,\n }\n}\n"],"names":["parseRelativeUrl","url","base","parseQuery","globalBase","URL","window","getLocationOrigin","resolvedBase","startsWith","location","href","pathname","searchParams","search","hash","origin","protocol","host","Error","auth","hostname","port","query","searchParamsToUrlQuery","undefined","slice","length","slashes"],"mappings":";;;;+BAkCgBA;;;eAAAA;;;uBAjCkB;6BACK;AAgChC,SAASA,iBACdC,GAAW,EACXC,IAAa,EACbC,aAAa,IAAI;IAEjB,MAAMC,aAAa,IAAIC,IACrB,OAAOC,WAAW,cAAc,aAAaC,IAAAA,wBAAiB;IAGhE,MAAMC,eAAeN,OACjB,IAAIG,IAAIH,MAAME,cACdH,IAAIQ,UAAU,CAAC,OACb,IAAIJ,IACF,OAAOC,WAAW,cAAc,aAAaA,OAAOI,QAAQ,CAACC,IAAI,IAEnEP;IAEN,MAAM,EAAEQ,QAAQ,EAAEC,YAAY,EAAEC,MAAM,EAAEC,IAAI,EAAEJ,IAAI,EAAEK,MAAM,EAAE,GAAGf,IAAIQ,UAAU,CAC3E,OAGE,kDAAkD;IAClD,gDAAgD;IAChD,IAAIJ,IAAI,GAAGG,aAAaS,QAAQ,CAAC,EAAE,EAAET,aAAaU,IAAI,GAAGjB,KAAK,IAC9D,IAAII,IAAIJ,KAAKO;IAEjB,IAAIQ,WAAWZ,WAAWY,MAAM,EAAE;QAChC,MAAM,IAAIG,MAAM,CAAC,iDAAiD,EAAElB,KAAK;IAC3E;IAEA,OAAO;QACLmB,MAAM;QACNF,MAAM;QACNG,UAAU;QACVT;QACAU,MAAM;QACNL,UAAU;QACVM,OAAOpB,aAAaqB,IAAAA,mCAAsB,EAACX,gBAAgBY;QAC3DX;QACAC;QACAJ,MAAMA,KAAKe,KAAK,CAACV,OAAOW,MAAM;QAC9B,gFAAgF;QAChF,qCAAqC;QACrCC,SAAS;IACX;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d0cabc744911cdfae1d89b91c537f9eb7ac0658 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.d.ts @@ -0,0 +1,15 @@ +import type { ParsedUrlQuery } from 'querystring'; +export interface ParsedUrl { + auth: string | null; + hash: string; + hostname: string | null; + href: string; + origin?: string | null; + pathname: string; + port: string | null; + protocol: string | null; + query: ParsedUrlQuery; + search: string; + slashes: boolean | null; +} +export declare function parseUrl(url: string): ParsedUrl; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.js new file mode 100644 index 0000000000000000000000000000000000000000..47c95163f8da8c0b0c5610a0d612c257fec978d0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "parseUrl", { + enumerable: true, + get: function() { + return parseUrl; + } +}); +const _querystring = require("./querystring"); +const _parserelativeurl = require("./parse-relative-url"); +function parseUrl(url) { + if (url.startsWith('/')) { + return (0, _parserelativeurl.parseRelativeUrl)(url); + } + const parsedURL = new URL(url); + const username = parsedURL.username; + const password = parsedURL.password; + const auth = username ? password ? `${username}:${password}` : username : null; + const pathname = parsedURL.pathname; + const search = parsedURL.search; + return { + auth, + hash: parsedURL.hash, + hostname: parsedURL.hostname, + href: parsedURL.href, + pathname, + port: parsedURL.port, + protocol: parsedURL.protocol, + query: (0, _querystring.searchParamsToUrlQuery)(parsedURL.searchParams), + search, + origin: parsedURL.origin, + slashes: parsedURL.href.slice(parsedURL.protocol.length, parsedURL.protocol.length + 2) === '//' + }; +} + +//# sourceMappingURL=parse-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cf3001f8dd4ccbcd565c25c0cfc923c3a119b6ff --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/parse-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/parse-url.ts"],"sourcesContent":["import type { ParsedUrlQuery } from 'querystring'\n\nimport { searchParamsToUrlQuery } from './querystring'\nimport { parseRelativeUrl } from './parse-relative-url'\n\nexport interface ParsedUrl {\n auth: string | null\n hash: string\n hostname: string | null\n href: string\n origin?: string | null\n pathname: string\n port: string | null\n protocol: string | null\n query: ParsedUrlQuery\n search: string\n slashes: boolean | null\n}\n\nexport function parseUrl(url: string): ParsedUrl {\n if (url.startsWith('/')) {\n return parseRelativeUrl(url)\n }\n\n const parsedURL = new URL(url)\n const username = parsedURL.username\n const password = parsedURL.password\n const auth = username\n ? password\n ? `${username}:${password}`\n : username\n : null\n const pathname = parsedURL.pathname\n const search = parsedURL.search\n return {\n auth,\n hash: parsedURL.hash,\n hostname: parsedURL.hostname,\n href: parsedURL.href,\n pathname,\n port: parsedURL.port,\n protocol: parsedURL.protocol,\n query: searchParamsToUrlQuery(parsedURL.searchParams),\n search,\n origin: parsedURL.origin,\n slashes:\n parsedURL.href.slice(\n parsedURL.protocol.length,\n parsedURL.protocol.length + 2\n ) === '//',\n }\n}\n"],"names":["parseUrl","url","startsWith","parseRelativeUrl","parsedURL","URL","username","password","auth","pathname","search","hash","hostname","href","port","protocol","query","searchParamsToUrlQuery","searchParams","origin","slashes","slice","length"],"mappings":";;;;+BAmBgBA;;;eAAAA;;;6BAjBuB;kCACN;AAgB1B,SAASA,SAASC,GAAW;IAClC,IAAIA,IAAIC,UAAU,CAAC,MAAM;QACvB,OAAOC,IAAAA,kCAAgB,EAACF;IAC1B;IAEA,MAAMG,YAAY,IAAIC,IAAIJ;IAC1B,MAAMK,WAAWF,UAAUE,QAAQ;IACnC,MAAMC,WAAWH,UAAUG,QAAQ;IACnC,MAAMC,OAAOF,WACTC,WACE,GAAGD,SAAS,CAAC,EAAEC,UAAU,GACzBD,WACF;IACJ,MAAMG,WAAWL,UAAUK,QAAQ;IACnC,MAAMC,SAASN,UAAUM,MAAM;IAC/B,OAAO;QACLF;QACAG,MAAMP,UAAUO,IAAI;QACpBC,UAAUR,UAAUQ,QAAQ;QAC5BC,MAAMT,UAAUS,IAAI;QACpBJ;QACAK,MAAMV,UAAUU,IAAI;QACpBC,UAAUX,UAAUW,QAAQ;QAC5BC,OAAOC,IAAAA,mCAAsB,EAACb,UAAUc,YAAY;QACpDR;QACAS,QAAQf,UAAUe,MAAM;QACxBC,SACEhB,UAAUS,IAAI,CAACQ,KAAK,CAClBjB,UAAUW,QAAQ,CAACO,MAAM,EACzBlB,UAAUW,QAAQ,CAACO,MAAM,GAAG,OACxB;IACV;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85550efefb8798df4972b9252fec238a12e598e6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.d.ts @@ -0,0 +1,8 @@ +/** + * Checks if a given path starts with a given prefix. It ensures it matches + * exactly without containing extra chars. e.g. prefix /docs should replace + * for /docs, /docs/, /docs/a but not /docsss + * @param path The path to check. + * @param prefix The prefix to check against. + */ +export declare function pathHasPrefix(path: string, prefix: string): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js new file mode 100644 index 0000000000000000000000000000000000000000..48faa494c1b9b5576456524cb5c469bd5b1e8dc9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "pathHasPrefix", { + enumerable: true, + get: function() { + return pathHasPrefix; + } +}); +const _parsepath = require("./parse-path"); +function pathHasPrefix(path, prefix) { + if (typeof path !== 'string') { + return false; + } + const { pathname } = (0, _parsepath.parsePath)(path); + return pathname === prefix || pathname.startsWith(prefix + '/'); +} + +//# sourceMappingURL=path-has-prefix.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2a2be7b6e2ada8dacebfe326a9a2072cfdcde819 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/path-has-prefix.ts"],"sourcesContent":["import { parsePath } from './parse-path'\n\n/**\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nexport function pathHasPrefix(path: string, prefix: string) {\n if (typeof path !== 'string') {\n return false\n }\n\n const { pathname } = parsePath(path)\n return pathname === prefix || pathname.startsWith(prefix + '/')\n}\n"],"names":["pathHasPrefix","path","prefix","pathname","parsePath","startsWith"],"mappings":";;;;+BASgBA;;;eAAAA;;;2BATU;AASnB,SAASA,cAAcC,IAAY,EAAEC,MAAc;IACxD,IAAI,OAAOD,SAAS,UAAU;QAC5B,OAAO;IACT;IAEA,MAAM,EAAEE,QAAQ,EAAE,GAAGC,IAAAA,oBAAS,EAACH;IAC/B,OAAOE,aAAaD,UAAUC,SAASE,UAAU,CAACH,SAAS;AAC7D","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d5ce8e2979ac9ef89d733f96caa96b6b9becde6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.d.ts @@ -0,0 +1,29 @@ +interface Options { + /** + * A transformer function that will be applied to the regexp generated + * from the provided path and path-to-regexp. + */ + regexModifier?: (regex: string) => string; + /** + * When true the function will remove all unnamed parameters + * from the matched parameters. + */ + removeUnnamedParams?: boolean; + /** + * When true the regexp won't allow an optional trailing delimiter + * to match. + */ + strict?: boolean; + /** + * When true the matcher will be case-sensitive, defaults to false + */ + sensitive?: boolean; +} +export type PatchMatcher = (pathname: string, params?: Record) => Record | false; +/** + * Generates a path matcher function for a given path and options based on + * path-to-regexp. By default the match will be case insensitive, non strict + * and delimited by `/`. + */ +export declare function getPathMatch(path: string, options?: Options): PatchMatcher; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.js new file mode 100644 index 0000000000000000000000000000000000000000..52db44b9f38991cd76f0c41ba7d11650289347ee --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getPathMatch", { + enumerable: true, + get: function() { + return getPathMatch; + } +}); +const _pathtoregexp = require("next/dist/compiled/path-to-regexp"); +function getPathMatch(path, options) { + const keys = []; + const regexp = (0, _pathtoregexp.pathToRegexp)(path, keys, { + delimiter: '/', + sensitive: typeof options?.sensitive === 'boolean' ? options.sensitive : false, + strict: options?.strict + }); + const matcher = (0, _pathtoregexp.regexpToFunction)(options?.regexModifier ? new RegExp(options.regexModifier(regexp.source), regexp.flags) : regexp, keys); + /** + * A matcher function that will check if a given pathname matches the path + * given in the builder function. When the path does not match it will return + * `false` but if it does it will return an object with the matched params + * merged with the params provided in the second argument. + */ return (pathname, params)=>{ + // If no pathname is provided it's not a match. + if (typeof pathname !== 'string') return false; + const match = matcher(pathname); + // If the path did not match `false` will be returned. + if (!match) return false; + /** + * If unnamed params are not allowed they must be removed from + * the matched parameters. path-to-regexp uses "string" for named and + * "number" for unnamed parameters. + */ if (options?.removeUnnamedParams) { + for (const key of keys){ + if (typeof key.name === 'number') { + delete match.params[key.name]; + } + } + } + return { + ...params, + ...match.params + }; + }; +} + +//# sourceMappingURL=path-match.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4fe2872513336efc6ab4809a15cf8c6ec715d720 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/path-match.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/path-match.ts"],"sourcesContent":["import type { Key } from 'next/dist/compiled/path-to-regexp'\nimport { regexpToFunction } from 'next/dist/compiled/path-to-regexp'\nimport { pathToRegexp } from 'next/dist/compiled/path-to-regexp'\n\ninterface Options {\n /**\n * A transformer function that will be applied to the regexp generated\n * from the provided path and path-to-regexp.\n */\n regexModifier?: (regex: string) => string\n /**\n * When true the function will remove all unnamed parameters\n * from the matched parameters.\n */\n removeUnnamedParams?: boolean\n /**\n * When true the regexp won't allow an optional trailing delimiter\n * to match.\n */\n strict?: boolean\n\n /**\n * When true the matcher will be case-sensitive, defaults to false\n */\n sensitive?: boolean\n}\n\nexport type PatchMatcher = (\n pathname: string,\n params?: Record\n) => Record | false\n\n/**\n * Generates a path matcher function for a given path and options based on\n * path-to-regexp. By default the match will be case insensitive, non strict\n * and delimited by `/`.\n */\nexport function getPathMatch(path: string, options?: Options): PatchMatcher {\n const keys: Key[] = []\n const regexp = pathToRegexp(path, keys, {\n delimiter: '/',\n sensitive:\n typeof options?.sensitive === 'boolean' ? options.sensitive : false,\n strict: options?.strict,\n })\n\n const matcher = regexpToFunction>(\n options?.regexModifier\n ? new RegExp(options.regexModifier(regexp.source), regexp.flags)\n : regexp,\n keys\n )\n\n /**\n * A matcher function that will check if a given pathname matches the path\n * given in the builder function. When the path does not match it will return\n * `false` but if it does it will return an object with the matched params\n * merged with the params provided in the second argument.\n */\n return (pathname, params) => {\n // If no pathname is provided it's not a match.\n if (typeof pathname !== 'string') return false\n\n const match = matcher(pathname)\n\n // If the path did not match `false` will be returned.\n if (!match) return false\n\n /**\n * If unnamed params are not allowed they must be removed from\n * the matched parameters. path-to-regexp uses \"string\" for named and\n * \"number\" for unnamed parameters.\n */\n if (options?.removeUnnamedParams) {\n for (const key of keys) {\n if (typeof key.name === 'number') {\n delete match.params[key.name]\n }\n }\n }\n\n return { ...params, ...match.params }\n }\n}\n"],"names":["getPathMatch","path","options","keys","regexp","pathToRegexp","delimiter","sensitive","strict","matcher","regexpToFunction","regexModifier","RegExp","source","flags","pathname","params","match","removeUnnamedParams","key","name"],"mappings":";;;;+BAqCgBA;;;eAAAA;;;8BApCiB;AAoC1B,SAASA,aAAaC,IAAY,EAAEC,OAAiB;IAC1D,MAAMC,OAAc,EAAE;IACtB,MAAMC,SAASC,IAAAA,0BAAY,EAACJ,MAAME,MAAM;QACtCG,WAAW;QACXC,WACE,OAAOL,SAASK,cAAc,YAAYL,QAAQK,SAAS,GAAG;QAChEC,QAAQN,SAASM;IACnB;IAEA,MAAMC,UAAUC,IAAAA,8BAAgB,EAC9BR,SAASS,gBACL,IAAIC,OAAOV,QAAQS,aAAa,CAACP,OAAOS,MAAM,GAAGT,OAAOU,KAAK,IAC7DV,QACJD;IAGF;;;;;GAKC,GACD,OAAO,CAACY,UAAUC;QAChB,+CAA+C;QAC/C,IAAI,OAAOD,aAAa,UAAU,OAAO;QAEzC,MAAME,QAAQR,QAAQM;QAEtB,sDAAsD;QACtD,IAAI,CAACE,OAAO,OAAO;QAEnB;;;;KAIC,GACD,IAAIf,SAASgB,qBAAqB;YAChC,KAAK,MAAMC,OAAOhB,KAAM;gBACtB,IAAI,OAAOgB,IAAIC,IAAI,KAAK,UAAU;oBAChC,OAAOH,MAAMD,MAAM,CAACG,IAAIC,IAAI,CAAC;gBAC/B;YACF;QACF;QAEA,OAAO;YAAE,GAAGJ,MAAM;YAAE,GAAGC,MAAMD,MAAM;QAAC;IACtC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..507a50d9227a6d364bbbaedf515883de91036db2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.d.ts @@ -0,0 +1,23 @@ +import type { IncomingMessage } from 'http'; +import type { NextParsedUrlQuery } from '../../../../server/request-meta'; +import type { RouteHas } from '../../../../lib/load-custom-routes'; +import type { BaseNextRequest } from '../../../../server/base-http'; +import { type ParsedUrl } from './parse-url'; +import type { Params } from '../../../../server/request/params'; +export declare function matchHas(req: BaseNextRequest | IncomingMessage, query: Params, has?: RouteHas[], missing?: RouteHas[]): false | Params; +export declare function compileNonPath(value: string, params: Params): string; +export declare function parseDestination(args: { + destination: string; + params: Readonly; + query: Readonly; +}): ParsedUrl; +export declare function prepareDestination(args: { + appendParamsToQuery: boolean; + destination: string; + params: Params; + query: NextParsedUrlQuery; +}): { + newUrl: string; + destQuery: import("querystring").ParsedUrlQuery; + parsedDestination: ParsedUrl; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.js new file mode 100644 index 0000000000000000000000000000000000000000..61c93083f0a1ac5122622e83475b0cc7bb85db85 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.js @@ -0,0 +1,289 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + compileNonPath: null, + matchHas: null, + parseDestination: null, + prepareDestination: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + compileNonPath: function() { + return compileNonPath; + }, + matchHas: function() { + return matchHas; + }, + parseDestination: function() { + return parseDestination; + }, + prepareDestination: function() { + return prepareDestination; + } +}); +const _escaperegexp = require("../../escape-regexp"); +const _parseurl = require("./parse-url"); +const _interceptionroutes = require("./interception-routes"); +const _getcookieparser = require("../../../../server/api-utils/get-cookie-parser"); +const _routematchutils = require("./route-match-utils"); +/** + * Ensure only a-zA-Z are used for param names for proper interpolating + * with path-to-regexp + */ function getSafeParamName(paramName) { + let newParamName = ''; + for(let i = 0; i < paramName.length; i++){ + const charCode = paramName.charCodeAt(i); + if (charCode > 64 && charCode < 91 || // A-Z + charCode > 96 && charCode < 123 // a-z + ) { + newParamName += paramName[i]; + } + } + return newParamName; +} +function escapeSegment(str, segmentName) { + return str.replace(new RegExp(`:${(0, _escaperegexp.escapeStringRegexp)(segmentName)}`, 'g'), `__ESC_COLON_${segmentName}`); +} +function unescapeSegments(str) { + return str.replace(/__ESC_COLON_/gi, ':'); +} +function matchHas(req, query, has = [], missing = []) { + const params = {}; + const hasMatch = (hasItem)=>{ + let value; + let key = hasItem.key; + switch(hasItem.type){ + case 'header': + { + key = key.toLowerCase(); + value = req.headers[key]; + break; + } + case 'cookie': + { + if ('cookies' in req) { + value = req.cookies[hasItem.key]; + } else { + const cookies = (0, _getcookieparser.getCookieParser)(req.headers)(); + value = cookies[hasItem.key]; + } + break; + } + case 'query': + { + value = query[key]; + break; + } + case 'host': + { + const { host } = req?.headers || {}; + // remove port from host if present + const hostname = host?.split(':', 1)[0].toLowerCase(); + value = hostname; + break; + } + default: + { + break; + } + } + if (!hasItem.value && value) { + params[getSafeParamName(key)] = value; + return true; + } else if (value) { + const matcher = new RegExp(`^${hasItem.value}$`); + const matches = Array.isArray(value) ? value.slice(-1)[0].match(matcher) : value.match(matcher); + if (matches) { + if (Array.isArray(matches)) { + if (matches.groups) { + Object.keys(matches.groups).forEach((groupKey)=>{ + params[groupKey] = matches.groups[groupKey]; + }); + } else if (hasItem.type === 'host' && matches[0]) { + params.host = matches[0]; + } + } + return true; + } + } + return false; + }; + const allMatch = has.every((item)=>hasMatch(item)) && !missing.some((item)=>hasMatch(item)); + if (allMatch) { + return params; + } + return false; +} +function compileNonPath(value, params) { + if (!value.includes(':')) { + return value; + } + for (const key of Object.keys(params)){ + if (value.includes(`:${key}`)) { + value = value.replace(new RegExp(`:${key}\\*`, 'g'), `:${key}--ESCAPED_PARAM_ASTERISKS`).replace(new RegExp(`:${key}\\?`, 'g'), `:${key}--ESCAPED_PARAM_QUESTION`).replace(new RegExp(`:${key}\\+`, 'g'), `:${key}--ESCAPED_PARAM_PLUS`).replace(new RegExp(`:${key}(?!\\w)`, 'g'), `--ESCAPED_PARAM_COLON${key}`); + } + } + value = value.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g, '\\$1').replace(/--ESCAPED_PARAM_PLUS/g, '+').replace(/--ESCAPED_PARAM_COLON/g, ':').replace(/--ESCAPED_PARAM_QUESTION/g, '?').replace(/--ESCAPED_PARAM_ASTERISKS/g, '*'); + // the value needs to start with a forward-slash to be compiled + // correctly + return (0, _routematchutils.safeCompile)(`/${value}`, { + validate: false + })(params).slice(1); +} +function parseDestination(args) { + let escaped = args.destination; + for (const param of Object.keys({ + ...args.params, + ...args.query + })){ + if (!param) continue; + escaped = escapeSegment(escaped, param); + } + const parsed = (0, _parseurl.parseUrl)(escaped); + let pathname = parsed.pathname; + if (pathname) { + pathname = unescapeSegments(pathname); + } + let href = parsed.href; + if (href) { + href = unescapeSegments(href); + } + let hostname = parsed.hostname; + if (hostname) { + hostname = unescapeSegments(hostname); + } + let hash = parsed.hash; + if (hash) { + hash = unescapeSegments(hash); + } + let search = parsed.search; + if (search) { + search = unescapeSegments(search); + } + let origin = parsed.origin; + if (origin) { + origin = unescapeSegments(origin); + } + return { + ...parsed, + pathname, + hostname, + href, + hash, + search, + origin + }; +} +function prepareDestination(args) { + const parsedDestination = parseDestination(args); + const { hostname: destHostname, query: destQuery, search: destSearch } = parsedDestination; + // The following code assumes that the pathname here includes the hash if it's + // present. + let destPath = parsedDestination.pathname; + if (parsedDestination.hash) { + destPath = `${destPath}${parsedDestination.hash}`; + } + const destParams = []; + const destPathParamKeys = []; + (0, _routematchutils.safePathToRegexp)(destPath, destPathParamKeys); + for (const key of destPathParamKeys){ + destParams.push(key.name); + } + if (destHostname) { + const destHostnameParamKeys = []; + (0, _routematchutils.safePathToRegexp)(destHostname, destHostnameParamKeys); + for (const key of destHostnameParamKeys){ + destParams.push(key.name); + } + } + const destPathCompiler = (0, _routematchutils.safeCompile)(destPath, // we don't validate while compiling the destination since we should + // have already validated before we got to this point and validating + // breaks compiling destinations with named pattern params from the source + // e.g. /something:hello(.*) -> /another/:hello is broken with validation + // since compile validation is meant for reversing and not for inserting + // params from a separate path-regex into another + { + validate: false + }); + let destHostnameCompiler; + if (destHostname) { + destHostnameCompiler = (0, _routematchutils.safeCompile)(destHostname, { + validate: false, + encode: encodeURIComponent + }); + } + // update any params in query values + for (const [key, strOrArray] of Object.entries(destQuery)){ + // the value needs to start with a forward-slash to be compiled + // correctly + if (Array.isArray(strOrArray)) { + destQuery[key] = strOrArray.map((value)=>compileNonPath(unescapeSegments(value), args.params)); + } else if (typeof strOrArray === 'string') { + destQuery[key] = compileNonPath(unescapeSegments(strOrArray), args.params); + } + } + // add path params to query if it's not a redirect and not + // already defined in destination query or path + let paramKeys = Object.keys(args.params).filter((name)=>name !== 'nextInternalLocale'); + if (args.appendParamsToQuery && !paramKeys.some((key)=>destParams.includes(key))) { + for (const key of paramKeys){ + if (!(key in destQuery)) { + destQuery[key] = args.params[key]; + } + } + } + let newUrl; + // The compiler also that the interception route marker is an unnamed param, hence '0', + // so we need to add it to the params object. + if ((0, _interceptionroutes.isInterceptionRouteAppPath)(destPath)) { + for (const segment of destPath.split('/')){ + const marker = _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m)); + if (marker) { + if (marker === '(..)(..)') { + args.params['0'] = '(..)'; + args.params['1'] = '(..)'; + } else { + args.params['0'] = marker; + } + break; + } + } + } + try { + newUrl = destPathCompiler(args.params); + const [pathname, hash] = newUrl.split('#', 2); + if (destHostnameCompiler) { + parsedDestination.hostname = destHostnameCompiler(args.params); + } + parsedDestination.pathname = pathname; + parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`; + parsedDestination.search = destSearch ? compileNonPath(destSearch, args.params) : ''; + } catch (err) { + if (err.message.match(/Expected .*? to not repeat, but got an array/)) { + throw new Error(`To use a multi-match in the destination you must add \`*\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match`); + } + throw err; + } + // Query merge order lowest priority to highest + // 1. initial URL query values + // 2. path segment values + // 3. destination specified query values + parsedDestination.query = { + ...args.query, + ...parsedDestination.query + }; + return { + newUrl, + destQuery, + parsedDestination + }; +} + +//# sourceMappingURL=prepare-destination.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.js.map new file mode 100644 index 0000000000000000000000000000000000000000..72dbde9d7c71f4b8db427c09095c074152fabe9a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/prepare-destination.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/prepare-destination.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\nimport type { Key } from 'next/dist/compiled/path-to-regexp'\nimport type { NextParsedUrlQuery } from '../../../../server/request-meta'\nimport type { RouteHas } from '../../../../lib/load-custom-routes'\nimport type { BaseNextRequest } from '../../../../server/base-http'\n\nimport { escapeStringRegexp } from '../../escape-regexp'\nimport { parseUrl, type ParsedUrl } from './parse-url'\nimport {\n INTERCEPTION_ROUTE_MARKERS,\n isInterceptionRouteAppPath,\n} from './interception-routes'\nimport { getCookieParser } from '../../../../server/api-utils/get-cookie-parser'\nimport type { Params } from '../../../../server/request/params'\nimport { safePathToRegexp, safeCompile } from './route-match-utils'\n\n/**\n * Ensure only a-zA-Z are used for param names for proper interpolating\n * with path-to-regexp\n */\nfunction getSafeParamName(paramName: string) {\n let newParamName = ''\n\n for (let i = 0; i < paramName.length; i++) {\n const charCode = paramName.charCodeAt(i)\n\n if (\n (charCode > 64 && charCode < 91) || // A-Z\n (charCode > 96 && charCode < 123) // a-z\n ) {\n newParamName += paramName[i]\n }\n }\n return newParamName\n}\n\nfunction escapeSegment(str: string, segmentName: string) {\n return str.replace(\n new RegExp(`:${escapeStringRegexp(segmentName)}`, 'g'),\n `__ESC_COLON_${segmentName}`\n )\n}\n\nfunction unescapeSegments(str: string) {\n return str.replace(/__ESC_COLON_/gi, ':')\n}\n\nexport function matchHas(\n req: BaseNextRequest | IncomingMessage,\n query: Params,\n has: RouteHas[] = [],\n missing: RouteHas[] = []\n): false | Params {\n const params: Params = {}\n\n const hasMatch = (hasItem: RouteHas) => {\n let value\n let key = hasItem.key\n\n switch (hasItem.type) {\n case 'header': {\n key = key!.toLowerCase()\n value = req.headers[key] as string\n break\n }\n case 'cookie': {\n if ('cookies' in req) {\n value = req.cookies[hasItem.key]\n } else {\n const cookies = getCookieParser(req.headers)()\n value = cookies[hasItem.key]\n }\n\n break\n }\n case 'query': {\n value = query[key!]\n break\n }\n case 'host': {\n const { host } = req?.headers || {}\n // remove port from host if present\n const hostname = host?.split(':', 1)[0].toLowerCase()\n value = hostname\n break\n }\n default: {\n break\n }\n }\n\n if (!hasItem.value && value) {\n params[getSafeParamName(key!)] = value\n return true\n } else if (value) {\n const matcher = new RegExp(`^${hasItem.value}$`)\n const matches = Array.isArray(value)\n ? value.slice(-1)[0].match(matcher)\n : value.match(matcher)\n\n if (matches) {\n if (Array.isArray(matches)) {\n if (matches.groups) {\n Object.keys(matches.groups).forEach((groupKey) => {\n params[groupKey] = matches.groups![groupKey]\n })\n } else if (hasItem.type === 'host' && matches[0]) {\n params.host = matches[0]\n }\n }\n return true\n }\n }\n return false\n }\n\n const allMatch =\n has.every((item) => hasMatch(item)) &&\n !missing.some((item) => hasMatch(item))\n\n if (allMatch) {\n return params\n }\n return false\n}\n\nexport function compileNonPath(value: string, params: Params): string {\n if (!value.includes(':')) {\n return value\n }\n\n for (const key of Object.keys(params)) {\n if (value.includes(`:${key}`)) {\n value = value\n .replace(\n new RegExp(`:${key}\\\\*`, 'g'),\n `:${key}--ESCAPED_PARAM_ASTERISKS`\n )\n .replace(\n new RegExp(`:${key}\\\\?`, 'g'),\n `:${key}--ESCAPED_PARAM_QUESTION`\n )\n .replace(new RegExp(`:${key}\\\\+`, 'g'), `:${key}--ESCAPED_PARAM_PLUS`)\n .replace(\n new RegExp(`:${key}(?!\\\\w)`, 'g'),\n `--ESCAPED_PARAM_COLON${key}`\n )\n }\n }\n value = value\n .replace(/(:|\\*|\\?|\\+|\\(|\\)|\\{|\\})/g, '\\\\$1')\n .replace(/--ESCAPED_PARAM_PLUS/g, '+')\n .replace(/--ESCAPED_PARAM_COLON/g, ':')\n .replace(/--ESCAPED_PARAM_QUESTION/g, '?')\n .replace(/--ESCAPED_PARAM_ASTERISKS/g, '*')\n\n // the value needs to start with a forward-slash to be compiled\n // correctly\n return safeCompile(`/${value}`, { validate: false })(params).slice(1)\n}\n\nexport function parseDestination(args: {\n destination: string\n params: Readonly\n query: Readonly\n}): ParsedUrl {\n let escaped = args.destination\n for (const param of Object.keys({ ...args.params, ...args.query })) {\n if (!param) continue\n\n escaped = escapeSegment(escaped, param)\n }\n\n const parsed = parseUrl(escaped)\n\n let pathname = parsed.pathname\n if (pathname) {\n pathname = unescapeSegments(pathname)\n }\n\n let href = parsed.href\n if (href) {\n href = unescapeSegments(href)\n }\n\n let hostname = parsed.hostname\n if (hostname) {\n hostname = unescapeSegments(hostname)\n }\n\n let hash = parsed.hash\n if (hash) {\n hash = unescapeSegments(hash)\n }\n\n let search = parsed.search\n if (search) {\n search = unescapeSegments(search)\n }\n\n let origin = parsed.origin\n if (origin) {\n origin = unescapeSegments(origin)\n }\n\n return {\n ...parsed,\n pathname,\n hostname,\n href,\n hash,\n search,\n origin,\n }\n}\n\nexport function prepareDestination(args: {\n appendParamsToQuery: boolean\n destination: string\n params: Params\n query: NextParsedUrlQuery\n}) {\n const parsedDestination = parseDestination(args)\n\n const {\n hostname: destHostname,\n query: destQuery,\n search: destSearch,\n } = parsedDestination\n\n // The following code assumes that the pathname here includes the hash if it's\n // present.\n let destPath = parsedDestination.pathname\n if (parsedDestination.hash) {\n destPath = `${destPath}${parsedDestination.hash}`\n }\n\n const destParams: (string | number)[] = []\n\n const destPathParamKeys: Key[] = []\n safePathToRegexp(destPath, destPathParamKeys)\n for (const key of destPathParamKeys) {\n destParams.push(key.name)\n }\n\n if (destHostname) {\n const destHostnameParamKeys: Key[] = []\n safePathToRegexp(destHostname, destHostnameParamKeys)\n for (const key of destHostnameParamKeys) {\n destParams.push(key.name)\n }\n }\n\n const destPathCompiler = safeCompile(\n destPath,\n // we don't validate while compiling the destination since we should\n // have already validated before we got to this point and validating\n // breaks compiling destinations with named pattern params from the source\n // e.g. /something:hello(.*) -> /another/:hello is broken with validation\n // since compile validation is meant for reversing and not for inserting\n // params from a separate path-regex into another\n { validate: false }\n )\n\n let destHostnameCompiler\n if (destHostname) {\n destHostnameCompiler = safeCompile(destHostname, {\n validate: false,\n encode: encodeURIComponent,\n })\n }\n\n // update any params in query values\n for (const [key, strOrArray] of Object.entries(destQuery)) {\n // the value needs to start with a forward-slash to be compiled\n // correctly\n if (Array.isArray(strOrArray)) {\n destQuery[key] = strOrArray.map((value) =>\n compileNonPath(unescapeSegments(value), args.params)\n )\n } else if (typeof strOrArray === 'string') {\n destQuery[key] = compileNonPath(unescapeSegments(strOrArray), args.params)\n }\n }\n\n // add path params to query if it's not a redirect and not\n // already defined in destination query or path\n let paramKeys = Object.keys(args.params).filter(\n (name) => name !== 'nextInternalLocale'\n )\n\n if (\n args.appendParamsToQuery &&\n !paramKeys.some((key) => destParams.includes(key))\n ) {\n for (const key of paramKeys) {\n if (!(key in destQuery)) {\n destQuery[key] = args.params[key]\n }\n }\n }\n\n let newUrl\n\n // The compiler also that the interception route marker is an unnamed param, hence '0',\n // so we need to add it to the params object.\n if (isInterceptionRouteAppPath(destPath)) {\n for (const segment of destPath.split('/')) {\n const marker = INTERCEPTION_ROUTE_MARKERS.find((m) =>\n segment.startsWith(m)\n )\n if (marker) {\n if (marker === '(..)(..)') {\n args.params['0'] = '(..)'\n args.params['1'] = '(..)'\n } else {\n args.params['0'] = marker\n }\n break\n }\n }\n }\n\n try {\n newUrl = destPathCompiler(args.params)\n\n const [pathname, hash] = newUrl.split('#', 2)\n if (destHostnameCompiler) {\n parsedDestination.hostname = destHostnameCompiler(args.params)\n }\n parsedDestination.pathname = pathname\n parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`\n parsedDestination.search = destSearch\n ? compileNonPath(destSearch, args.params)\n : ''\n } catch (err: any) {\n if (err.message.match(/Expected .*? to not repeat, but got an array/)) {\n throw new Error(\n `To use a multi-match in the destination you must add \\`*\\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match`\n )\n }\n throw err\n }\n\n // Query merge order lowest priority to highest\n // 1. initial URL query values\n // 2. path segment values\n // 3. destination specified query values\n parsedDestination.query = {\n ...args.query,\n ...parsedDestination.query,\n }\n\n return {\n newUrl,\n destQuery,\n parsedDestination,\n }\n}\n"],"names":["compileNonPath","matchHas","parseDestination","prepareDestination","getSafeParamName","paramName","newParamName","i","length","charCode","charCodeAt","escapeSegment","str","segmentName","replace","RegExp","escapeStringRegexp","unescapeSegments","req","query","has","missing","params","hasMatch","hasItem","value","key","type","toLowerCase","headers","cookies","getCookieParser","host","hostname","split","matcher","matches","Array","isArray","slice","match","groups","Object","keys","forEach","groupKey","allMatch","every","item","some","includes","safeCompile","validate","args","escaped","destination","param","parsed","parseUrl","pathname","href","hash","search","origin","parsedDestination","destHostname","destQuery","destSearch","destPath","destParams","destPathParamKeys","safePathToRegexp","push","name","destHostnameParamKeys","destPathCompiler","destHostnameCompiler","encode","encodeURIComponent","strOrArray","entries","map","paramKeys","filter","appendParamsToQuery","newUrl","isInterceptionRouteAppPath","segment","marker","INTERCEPTION_ROUTE_MARKERS","find","m","startsWith","err","message","Error"],"mappings":";;;;;;;;;;;;;;;;;IA8HgBA,cAAc;eAAdA;;IA/EAC,QAAQ;eAARA;;IAkHAC,gBAAgB;eAAhBA;;IAuDAC,kBAAkB;eAAlBA;;;8BAlNmB;0BACM;oCAIlC;iCACyB;iCAEc;AAE9C;;;CAGC,GACD,SAASC,iBAAiBC,SAAiB;IACzC,IAAIC,eAAe;IAEnB,IAAK,IAAIC,IAAI,GAAGA,IAAIF,UAAUG,MAAM,EAAED,IAAK;QACzC,MAAME,WAAWJ,UAAUK,UAAU,CAACH;QAEtC,IACE,AAACE,WAAW,MAAMA,WAAW,MAAO,MAAM;QACzCA,WAAW,MAAMA,WAAW,IAAK,MAAM;UACxC;YACAH,gBAAgBD,SAAS,CAACE,EAAE;QAC9B;IACF;IACA,OAAOD;AACT;AAEA,SAASK,cAAcC,GAAW,EAAEC,WAAmB;IACrD,OAAOD,IAAIE,OAAO,CAChB,IAAIC,OAAO,CAAC,CAAC,EAAEC,IAAAA,gCAAkB,EAACH,cAAc,EAAE,MAClD,CAAC,YAAY,EAAEA,aAAa;AAEhC;AAEA,SAASI,iBAAiBL,GAAW;IACnC,OAAOA,IAAIE,OAAO,CAAC,kBAAkB;AACvC;AAEO,SAASb,SACdiB,GAAsC,EACtCC,KAAa,EACbC,MAAkB,EAAE,EACpBC,UAAsB,EAAE;IAExB,MAAMC,SAAiB,CAAC;IAExB,MAAMC,WAAW,CAACC;QAChB,IAAIC;QACJ,IAAIC,MAAMF,QAAQE,GAAG;QAErB,OAAQF,QAAQG,IAAI;YAClB,KAAK;gBAAU;oBACbD,MAAMA,IAAKE,WAAW;oBACtBH,QAAQP,IAAIW,OAAO,CAACH,IAAI;oBACxB;gBACF;YACA,KAAK;gBAAU;oBACb,IAAI,aAAaR,KAAK;wBACpBO,QAAQP,IAAIY,OAAO,CAACN,QAAQE,GAAG,CAAC;oBAClC,OAAO;wBACL,MAAMI,UAAUC,IAAAA,gCAAe,EAACb,IAAIW,OAAO;wBAC3CJ,QAAQK,OAAO,CAACN,QAAQE,GAAG,CAAC;oBAC9B;oBAEA;gBACF;YACA,KAAK;gBAAS;oBACZD,QAAQN,KAAK,CAACO,IAAK;oBACnB;gBACF;YACA,KAAK;gBAAQ;oBACX,MAAM,EAAEM,IAAI,EAAE,GAAGd,KAAKW,WAAW,CAAC;oBAClC,mCAAmC;oBACnC,MAAMI,WAAWD,MAAME,MAAM,KAAK,EAAE,CAAC,EAAE,CAACN;oBACxCH,QAAQQ;oBACR;gBACF;YACA;gBAAS;oBACP;gBACF;QACF;QAEA,IAAI,CAACT,QAAQC,KAAK,IAAIA,OAAO;YAC3BH,MAAM,CAAClB,iBAAiBsB,KAAM,GAAGD;YACjC,OAAO;QACT,OAAO,IAAIA,OAAO;YAChB,MAAMU,UAAU,IAAIpB,OAAO,CAAC,CAAC,EAAES,QAAQC,KAAK,CAAC,CAAC,CAAC;YAC/C,MAAMW,UAAUC,MAAMC,OAAO,CAACb,SAC1BA,MAAMc,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAACC,KAAK,CAACL,WACzBV,MAAMe,KAAK,CAACL;YAEhB,IAAIC,SAAS;gBACX,IAAIC,MAAMC,OAAO,CAACF,UAAU;oBAC1B,IAAIA,QAAQK,MAAM,EAAE;wBAClBC,OAAOC,IAAI,CAACP,QAAQK,MAAM,EAAEG,OAAO,CAAC,CAACC;4BACnCvB,MAAM,CAACuB,SAAS,GAAGT,QAAQK,MAAM,AAAC,CAACI,SAAS;wBAC9C;oBACF,OAAO,IAAIrB,QAAQG,IAAI,KAAK,UAAUS,OAAO,CAAC,EAAE,EAAE;wBAChDd,OAAOU,IAAI,GAAGI,OAAO,CAAC,EAAE;oBAC1B;gBACF;gBACA,OAAO;YACT;QACF;QACA,OAAO;IACT;IAEA,MAAMU,WACJ1B,IAAI2B,KAAK,CAAC,CAACC,OAASzB,SAASyB,UAC7B,CAAC3B,QAAQ4B,IAAI,CAAC,CAACD,OAASzB,SAASyB;IAEnC,IAAIF,UAAU;QACZ,OAAOxB;IACT;IACA,OAAO;AACT;AAEO,SAAStB,eAAeyB,KAAa,EAAEH,MAAc;IAC1D,IAAI,CAACG,MAAMyB,QAAQ,CAAC,MAAM;QACxB,OAAOzB;IACT;IAEA,KAAK,MAAMC,OAAOgB,OAAOC,IAAI,CAACrB,QAAS;QACrC,IAAIG,MAAMyB,QAAQ,CAAC,CAAC,CAAC,EAAExB,KAAK,GAAG;YAC7BD,QAAQA,MACLX,OAAO,CACN,IAAIC,OAAO,CAAC,CAAC,EAAEW,IAAI,GAAG,CAAC,EAAE,MACzB,CAAC,CAAC,EAAEA,IAAI,yBAAyB,CAAC,EAEnCZ,OAAO,CACN,IAAIC,OAAO,CAAC,CAAC,EAAEW,IAAI,GAAG,CAAC,EAAE,MACzB,CAAC,CAAC,EAAEA,IAAI,wBAAwB,CAAC,EAElCZ,OAAO,CAAC,IAAIC,OAAO,CAAC,CAAC,EAAEW,IAAI,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,EAAEA,IAAI,oBAAoB,CAAC,EACpEZ,OAAO,CACN,IAAIC,OAAO,CAAC,CAAC,EAAEW,IAAI,OAAO,CAAC,EAAE,MAC7B,CAAC,qBAAqB,EAAEA,KAAK;QAEnC;IACF;IACAD,QAAQA,MACLX,OAAO,CAAC,6BAA6B,QACrCA,OAAO,CAAC,yBAAyB,KACjCA,OAAO,CAAC,0BAA0B,KAClCA,OAAO,CAAC,6BAA6B,KACrCA,OAAO,CAAC,8BAA8B;IAEzC,+DAA+D;IAC/D,YAAY;IACZ,OAAOqC,IAAAA,4BAAW,EAAC,CAAC,CAAC,EAAE1B,OAAO,EAAE;QAAE2B,UAAU;IAAM,GAAG9B,QAAQiB,KAAK,CAAC;AACrE;AAEO,SAASrC,iBAAiBmD,IAIhC;IACC,IAAIC,UAAUD,KAAKE,WAAW;IAC9B,KAAK,MAAMC,SAASd,OAAOC,IAAI,CAAC;QAAE,GAAGU,KAAK/B,MAAM;QAAE,GAAG+B,KAAKlC,KAAK;IAAC,GAAI;QAClE,IAAI,CAACqC,OAAO;QAEZF,UAAU3C,cAAc2C,SAASE;IACnC;IAEA,MAAMC,SAASC,IAAAA,kBAAQ,EAACJ;IAExB,IAAIK,WAAWF,OAAOE,QAAQ;IAC9B,IAAIA,UAAU;QACZA,WAAW1C,iBAAiB0C;IAC9B;IAEA,IAAIC,OAAOH,OAAOG,IAAI;IACtB,IAAIA,MAAM;QACRA,OAAO3C,iBAAiB2C;IAC1B;IAEA,IAAI3B,WAAWwB,OAAOxB,QAAQ;IAC9B,IAAIA,UAAU;QACZA,WAAWhB,iBAAiBgB;IAC9B;IAEA,IAAI4B,OAAOJ,OAAOI,IAAI;IACtB,IAAIA,MAAM;QACRA,OAAO5C,iBAAiB4C;IAC1B;IAEA,IAAIC,SAASL,OAAOK,MAAM;IAC1B,IAAIA,QAAQ;QACVA,SAAS7C,iBAAiB6C;IAC5B;IAEA,IAAIC,SAASN,OAAOM,MAAM;IAC1B,IAAIA,QAAQ;QACVA,SAAS9C,iBAAiB8C;IAC5B;IAEA,OAAO;QACL,GAAGN,MAAM;QACTE;QACA1B;QACA2B;QACAC;QACAC;QACAC;IACF;AACF;AAEO,SAAS5D,mBAAmBkD,IAKlC;IACC,MAAMW,oBAAoB9D,iBAAiBmD;IAE3C,MAAM,EACJpB,UAAUgC,YAAY,EACtB9C,OAAO+C,SAAS,EAChBJ,QAAQK,UAAU,EACnB,GAAGH;IAEJ,8EAA8E;IAC9E,WAAW;IACX,IAAII,WAAWJ,kBAAkBL,QAAQ;IACzC,IAAIK,kBAAkBH,IAAI,EAAE;QAC1BO,WAAW,GAAGA,WAAWJ,kBAAkBH,IAAI,EAAE;IACnD;IAEA,MAAMQ,aAAkC,EAAE;IAE1C,MAAMC,oBAA2B,EAAE;IACnCC,IAAAA,iCAAgB,EAACH,UAAUE;IAC3B,KAAK,MAAM5C,OAAO4C,kBAAmB;QACnCD,WAAWG,IAAI,CAAC9C,IAAI+C,IAAI;IAC1B;IAEA,IAAIR,cAAc;QAChB,MAAMS,wBAA+B,EAAE;QACvCH,IAAAA,iCAAgB,EAACN,cAAcS;QAC/B,KAAK,MAAMhD,OAAOgD,sBAAuB;YACvCL,WAAWG,IAAI,CAAC9C,IAAI+C,IAAI;QAC1B;IACF;IAEA,MAAME,mBAAmBxB,IAAAA,4BAAW,EAClCiB,UACA,oEAAoE;IACpE,oEAAoE;IACpE,0EAA0E;IAC1E,yEAAyE;IACzE,wEAAwE;IACxE,iDAAiD;IACjD;QAAEhB,UAAU;IAAM;IAGpB,IAAIwB;IACJ,IAAIX,cAAc;QAChBW,uBAAuBzB,IAAAA,4BAAW,EAACc,cAAc;YAC/Cb,UAAU;YACVyB,QAAQC;QACV;IACF;IAEA,oCAAoC;IACpC,KAAK,MAAM,CAACpD,KAAKqD,WAAW,IAAIrC,OAAOsC,OAAO,CAACd,WAAY;QACzD,+DAA+D;QAC/D,YAAY;QACZ,IAAI7B,MAAMC,OAAO,CAACyC,aAAa;YAC7Bb,SAAS,CAACxC,IAAI,GAAGqD,WAAWE,GAAG,CAAC,CAACxD,QAC/BzB,eAAeiB,iBAAiBQ,QAAQ4B,KAAK/B,MAAM;QAEvD,OAAO,IAAI,OAAOyD,eAAe,UAAU;YACzCb,SAAS,CAACxC,IAAI,GAAG1B,eAAeiB,iBAAiB8D,aAAa1B,KAAK/B,MAAM;QAC3E;IACF;IAEA,0DAA0D;IAC1D,+CAA+C;IAC/C,IAAI4D,YAAYxC,OAAOC,IAAI,CAACU,KAAK/B,MAAM,EAAE6D,MAAM,CAC7C,CAACV,OAASA,SAAS;IAGrB,IACEpB,KAAK+B,mBAAmB,IACxB,CAACF,UAAUjC,IAAI,CAAC,CAACvB,MAAQ2C,WAAWnB,QAAQ,CAACxB,OAC7C;QACA,KAAK,MAAMA,OAAOwD,UAAW;YAC3B,IAAI,CAAExD,CAAAA,OAAOwC,SAAQ,GAAI;gBACvBA,SAAS,CAACxC,IAAI,GAAG2B,KAAK/B,MAAM,CAACI,IAAI;YACnC;QACF;IACF;IAEA,IAAI2D;IAEJ,uFAAuF;IACvF,6CAA6C;IAC7C,IAAIC,IAAAA,8CAA0B,EAAClB,WAAW;QACxC,KAAK,MAAMmB,WAAWnB,SAASlC,KAAK,CAAC,KAAM;YACzC,MAAMsD,SAASC,8CAA0B,CAACC,IAAI,CAAC,CAACC,IAC9CJ,QAAQK,UAAU,CAACD;YAErB,IAAIH,QAAQ;gBACV,IAAIA,WAAW,YAAY;oBACzBnC,KAAK/B,MAAM,CAAC,IAAI,GAAG;oBACnB+B,KAAK/B,MAAM,CAAC,IAAI,GAAG;gBACrB,OAAO;oBACL+B,KAAK/B,MAAM,CAAC,IAAI,GAAGkE;gBACrB;gBACA;YACF;QACF;IACF;IAEA,IAAI;QACFH,SAASV,iBAAiBtB,KAAK/B,MAAM;QAErC,MAAM,CAACqC,UAAUE,KAAK,GAAGwB,OAAOnD,KAAK,CAAC,KAAK;QAC3C,IAAI0C,sBAAsB;YACxBZ,kBAAkB/B,QAAQ,GAAG2C,qBAAqBvB,KAAK/B,MAAM;QAC/D;QACA0C,kBAAkBL,QAAQ,GAAGA;QAC7BK,kBAAkBH,IAAI,GAAG,GAAGA,OAAO,MAAM,KAAKA,QAAQ,IAAI;QAC1DG,kBAAkBF,MAAM,GAAGK,aACvBnE,eAAemE,YAAYd,KAAK/B,MAAM,IACtC;IACN,EAAE,OAAOuE,KAAU;QACjB,IAAIA,IAAIC,OAAO,CAACtD,KAAK,CAAC,iDAAiD;YACrE,MAAM,IAAIuD,MACR,CAAC,yKAAyK,CAAC;QAE/K;QACA,MAAMF;IACR;IAEA,+CAA+C;IAC/C,8BAA8B;IAC9B,yBAAyB;IACzB,wCAAwC;IACxC7B,kBAAkB7C,KAAK,GAAG;QACxB,GAAGkC,KAAKlC,KAAK;QACb,GAAG6C,kBAAkB7C,KAAK;IAC5B;IAEA,OAAO;QACLkE;QACAnB;QACAF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..debb3abb8eb19c0611fad88a394a76c141c8967b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.d.ts @@ -0,0 +1,5 @@ +import type { ParsedUrlQuery } from 'querystring'; +export declare function getRenderedSearch(query: ParsedUrlQuery): string; +export declare function searchParamsToUrlQuery(searchParams: URLSearchParams): ParsedUrlQuery; +export declare function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams; +export declare function assign(target: URLSearchParams, ...searchParamsList: URLSearchParams[]): URLSearchParams; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.js new file mode 100644 index 0000000000000000000000000000000000000000..e2866fb47d0c1a86343a393a9d7b0bf37ba1acff --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.js @@ -0,0 +1,110 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + assign: null, + getRenderedSearch: null, + searchParamsToUrlQuery: null, + urlQueryToSearchParams: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + assign: function() { + return assign; + }, + getRenderedSearch: function() { + return getRenderedSearch; + }, + searchParamsToUrlQuery: function() { + return searchParamsToUrlQuery; + }, + urlQueryToSearchParams: function() { + return urlQueryToSearchParams; + } +}); +function getRenderedSearch(query) { + // Inlined implementation of querystring.encode, which is not available in + // the Edge runtime. + const pairs = []; + for(const key in query){ + const value = query[key]; + if (value == null) continue; + if (Array.isArray(value)) { + for (const v of value){ + pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`); + } + } else { + pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); + } + } + // The result should match the format of a web URL's `search` property, since + // this is the format that's stored in the App Router state. + // TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query + // header omits the leading question mark. Should refactor to always do + // that instead. + if (pairs.length === 0) { + // If the search string is empty, return an empty string. + return ''; + } + // Prepend '?' to the search params string. + return '?' + pairs.join('&'); +} +function searchParamsToUrlQuery(searchParams) { + const query = {}; + for (const [key, value] of searchParams.entries()){ + const existing = query[key]; + if (typeof existing === 'undefined') { + query[key] = value; + } else if (Array.isArray(existing)) { + existing.push(value); + } else { + query[key] = [ + existing, + value + ]; + } + } + return query; +} +function stringifyUrlQueryParam(param) { + if (typeof param === 'string') { + return param; + } + if (typeof param === 'number' && !isNaN(param) || typeof param === 'boolean') { + return String(param); + } else { + return ''; + } +} +function urlQueryToSearchParams(query) { + const searchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(query)){ + if (Array.isArray(value)) { + for (const item of value){ + searchParams.append(key, stringifyUrlQueryParam(item)); + } + } else { + searchParams.set(key, stringifyUrlQueryParam(value)); + } + } + return searchParams; +} +function assign(target, ...searchParamsList) { + for (const searchParams of searchParamsList){ + for (const key of searchParams.keys()){ + target.delete(key); + } + for (const [key, value] of searchParams.entries()){ + target.append(key, value); + } + } + return target; +} + +//# sourceMappingURL=querystring.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cc76398a0adb3ac5845bb2e8ba863fae7025eb2d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/querystring.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/querystring.ts"],"sourcesContent":["import type { ParsedUrlQuery } from 'querystring'\n\nexport function getRenderedSearch(query: ParsedUrlQuery): string {\n // Inlined implementation of querystring.encode, which is not available in\n // the Edge runtime.\n const pairs = []\n for (const key in query) {\n const value = query[key]\n if (value == null) continue\n if (Array.isArray(value)) {\n for (const v of value) {\n pairs.push(\n `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n }\n } else {\n pairs.push(\n `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`\n )\n }\n }\n\n // The result should match the format of a web URL's `search` property, since\n // this is the format that's stored in the App Router state.\n // TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query\n // header omits the leading question mark. Should refactor to always do\n // that instead.\n if (pairs.length === 0) {\n // If the search string is empty, return an empty string.\n return ''\n }\n // Prepend '?' to the search params string.\n return '?' + pairs.join('&')\n}\n\nexport function searchParamsToUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n const query: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n const existing = query[key]\n if (typeof existing === 'undefined') {\n query[key] = value\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n query[key] = [existing, value]\n }\n }\n return query\n}\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n if (typeof param === 'string') {\n return param\n }\n\n if (\n (typeof param === 'number' && !isNaN(param)) ||\n typeof param === 'boolean'\n ) {\n return String(param)\n } else {\n return ''\n }\n}\n\nexport function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, stringifyUrlQueryParam(item))\n }\n } else {\n searchParams.set(key, stringifyUrlQueryParam(value))\n }\n }\n return searchParams\n}\n\nexport function assign(\n target: URLSearchParams,\n ...searchParamsList: URLSearchParams[]\n): URLSearchParams {\n for (const searchParams of searchParamsList) {\n for (const key of searchParams.keys()) {\n target.delete(key)\n }\n\n for (const [key, value] of searchParams.entries()) {\n target.append(key, value)\n }\n }\n\n return target\n}\n"],"names":["assign","getRenderedSearch","searchParamsToUrlQuery","urlQueryToSearchParams","query","pairs","key","value","Array","isArray","v","push","encodeURIComponent","String","length","join","searchParams","entries","existing","stringifyUrlQueryParam","param","isNaN","URLSearchParams","Object","item","append","set","target","searchParamsList","keys","delete"],"mappings":";;;;;;;;;;;;;;;;;IAiFgBA,MAAM;eAANA;;IA/EAC,iBAAiB;eAAjBA;;IAiCAC,sBAAsB;eAAtBA;;IAgCAC,sBAAsB;eAAtBA;;;AAjET,SAASF,kBAAkBG,KAAqB;IACrD,0EAA0E;IAC1E,oBAAoB;IACpB,MAAMC,QAAQ,EAAE;IAChB,IAAK,MAAMC,OAAOF,MAAO;QACvB,MAAMG,QAAQH,KAAK,CAACE,IAAI;QACxB,IAAIC,SAAS,MAAM;QACnB,IAAIC,MAAMC,OAAO,CAACF,QAAQ;YACxB,KAAK,MAAMG,KAAKH,MAAO;gBACrBF,MAAMM,IAAI,CACR,GAAGC,mBAAmBN,KAAK,CAAC,EAAEM,mBAAmBC,OAAOH,KAAK;YAEjE;QACF,OAAO;YACLL,MAAMM,IAAI,CACR,GAAGC,mBAAmBN,KAAK,CAAC,EAAEM,mBAAmBC,OAAON,SAAS;QAErE;IACF;IAEA,6EAA6E;IAC7E,4DAA4D;IAC5D,0EAA0E;IAC1E,uEAAuE;IACvE,gBAAgB;IAChB,IAAIF,MAAMS,MAAM,KAAK,GAAG;QACtB,yDAAyD;QACzD,OAAO;IACT;IACA,2CAA2C;IAC3C,OAAO,MAAMT,MAAMU,IAAI,CAAC;AAC1B;AAEO,SAASb,uBACdc,YAA6B;IAE7B,MAAMZ,QAAwB,CAAC;IAC/B,KAAK,MAAM,CAACE,KAAKC,MAAM,IAAIS,aAAaC,OAAO,GAAI;QACjD,MAAMC,WAAWd,KAAK,CAACE,IAAI;QAC3B,IAAI,OAAOY,aAAa,aAAa;YACnCd,KAAK,CAACE,IAAI,GAAGC;QACf,OAAO,IAAIC,MAAMC,OAAO,CAACS,WAAW;YAClCA,SAASP,IAAI,CAACJ;QAChB,OAAO;YACLH,KAAK,CAACE,IAAI,GAAG;gBAACY;gBAAUX;aAAM;QAChC;IACF;IACA,OAAOH;AACT;AAEA,SAASe,uBAAuBC,KAAc;IAC5C,IAAI,OAAOA,UAAU,UAAU;QAC7B,OAAOA;IACT;IAEA,IACE,AAAC,OAAOA,UAAU,YAAY,CAACC,MAAMD,UACrC,OAAOA,UAAU,WACjB;QACA,OAAOP,OAAOO;IAChB,OAAO;QACL,OAAO;IACT;AACF;AAEO,SAASjB,uBAAuBC,KAAqB;IAC1D,MAAMY,eAAe,IAAIM;IACzB,KAAK,MAAM,CAAChB,KAAKC,MAAM,IAAIgB,OAAON,OAAO,CAACb,OAAQ;QAChD,IAAII,MAAMC,OAAO,CAACF,QAAQ;YACxB,KAAK,MAAMiB,QAAQjB,MAAO;gBACxBS,aAAaS,MAAM,CAACnB,KAAKa,uBAAuBK;YAClD;QACF,OAAO;YACLR,aAAaU,GAAG,CAACpB,KAAKa,uBAAuBZ;QAC/C;IACF;IACA,OAAOS;AACT;AAEO,SAAShB,OACd2B,MAAuB,EACvB,GAAGC,gBAAmC;IAEtC,KAAK,MAAMZ,gBAAgBY,iBAAkB;QAC3C,KAAK,MAAMtB,OAAOU,aAAaa,IAAI,GAAI;YACrCF,OAAOG,MAAM,CAACxB;QAChB;QAEA,KAAK,MAAM,CAACA,KAAKC,MAAM,IAAIS,aAAaC,OAAO,GAAI;YACjDU,OAAOF,MAAM,CAACnB,KAAKC;QACrB;IACF;IAEA,OAAOoB;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..518a504ca90c1aa8bee89909dfa0e5c390f7db17 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.d.ts @@ -0,0 +1,20 @@ +/** + * The result of parsing a URL relative to a base URL. + */ +export type RelativeURL = { + /** + * The relative URL. Either a URL including the origin or a relative URL. + */ + url: string; + /** + * Whether the URL is relative to the base URL. + */ + isRelative: boolean; +}; +export declare function parseRelativeURL(url: string | URL, base: string | URL): RelativeURL; +/** + * Given a URL as a string and a base URL it will make the URL relative + * if the parsed protocol and host is the same as the one in the base + * URL. Otherwise it returns the same URL string. + */ +export declare function getRelativeURL(url: string | URL, base: string | URL): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.js new file mode 100644 index 0000000000000000000000000000000000000000..8c9be378ffbc91d6769ca64054667986b24a4fc2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.js @@ -0,0 +1,40 @@ +/** + * The result of parsing a URL relative to a base URL. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getRelativeURL: null, + parseRelativeURL: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getRelativeURL: function() { + return getRelativeURL; + }, + parseRelativeURL: function() { + return parseRelativeURL; + } +}); +function parseRelativeURL(url, base) { + const baseURL = typeof base === 'string' ? new URL(base) : base; + const relative = new URL(url, base); + // The URL is relative if the origin is the same as the base URL. + const isRelative = relative.origin === baseURL.origin; + return { + url: isRelative ? relative.toString().slice(baseURL.origin.length) : relative.toString(), + isRelative + }; +} +function getRelativeURL(url, base) { + const relative = parseRelativeURL(url, base); + return relative.url; +} + +//# sourceMappingURL=relativize-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dc4b98778fadc34efa6ee9bfc5607047ad06a128 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/relativize-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/relativize-url.ts"],"sourcesContent":["/**\n * The result of parsing a URL relative to a base URL.\n */\nexport type RelativeURL = {\n /**\n * The relative URL. Either a URL including the origin or a relative URL.\n */\n url: string\n\n /**\n * Whether the URL is relative to the base URL.\n */\n isRelative: boolean\n}\n\nexport function parseRelativeURL(\n url: string | URL,\n base: string | URL\n): RelativeURL {\n const baseURL = typeof base === 'string' ? new URL(base) : base\n const relative = new URL(url, base)\n\n // The URL is relative if the origin is the same as the base URL.\n const isRelative = relative.origin === baseURL.origin\n\n return {\n url: isRelative\n ? relative.toString().slice(baseURL.origin.length)\n : relative.toString(),\n isRelative,\n }\n}\n\n/**\n * Given a URL as a string and a base URL it will make the URL relative\n * if the parsed protocol and host is the same as the one in the base\n * URL. Otherwise it returns the same URL string.\n */\nexport function getRelativeURL(url: string | URL, base: string | URL): string {\n const relative = parseRelativeURL(url, base)\n return relative.url\n}\n"],"names":["getRelativeURL","parseRelativeURL","url","base","baseURL","URL","relative","isRelative","origin","toString","slice","length"],"mappings":"AAAA;;CAEC;;;;;;;;;;;;;;;IAoCeA,cAAc;eAAdA;;IAvBAC,gBAAgB;eAAhBA;;;AAAT,SAASA,iBACdC,GAAiB,EACjBC,IAAkB;IAElB,MAAMC,UAAU,OAAOD,SAAS,WAAW,IAAIE,IAAIF,QAAQA;IAC3D,MAAMG,WAAW,IAAID,IAAIH,KAAKC;IAE9B,iEAAiE;IACjE,MAAMI,aAAaD,SAASE,MAAM,KAAKJ,QAAQI,MAAM;IAErD,OAAO;QACLN,KAAKK,aACDD,SAASG,QAAQ,GAAGC,KAAK,CAACN,QAAQI,MAAM,CAACG,MAAM,IAC/CL,SAASG,QAAQ;QACrBF;IACF;AACF;AAOO,SAASP,eAAeE,GAAiB,EAAEC,IAAkB;IAClE,MAAMG,WAAWL,iBAAiBC,KAAKC;IACvC,OAAOG,SAASJ,GAAG;AACrB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b2a2d3e3e1cc65d7ac85916318c38e33dcd74d5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.d.ts @@ -0,0 +1,9 @@ +/** + * Given a path and a prefix it will remove the prefix when it exists in the + * given path. It ensures it matches exactly without containing extra chars + * and if the prefix is not there it will be noop. + * + * @param path The path to remove the prefix from. + * @param prefix The prefix to be removed. + */ +export declare function removePathPrefix(path: string, prefix: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js new file mode 100644 index 0000000000000000000000000000000000000000..4ee056fe2139ffb14f4947292a2f29ea5350046f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "removePathPrefix", { + enumerable: true, + get: function() { + return removePathPrefix; + } +}); +const _pathhasprefix = require("./path-has-prefix"); +function removePathPrefix(path, prefix) { + // If the path doesn't start with the prefix we can return it as is. This + // protects us from situations where the prefix is a substring of the path + // prefix such as: + // + // For prefix: /blog + // + // /blog -> true + // /blog/ -> true + // /blog/1 -> true + // /blogging -> false + // /blogging/ -> false + // /blogging/1 -> false + if (!(0, _pathhasprefix.pathHasPrefix)(path, prefix)) { + return path; + } + // Remove the prefix from the path via slicing. + const withoutPrefix = path.slice(prefix.length); + // If the path without the prefix starts with a `/` we can return it as is. + if (withoutPrefix.startsWith('/')) { + return withoutPrefix; + } + // If the path without the prefix doesn't start with a `/` we need to add it + // back to the path to make sure it's a valid path. + return `/${withoutPrefix}`; +} + +//# sourceMappingURL=remove-path-prefix.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6e272396e85d6bec17b3db75e3d45e71bdd0d443 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/remove-path-prefix.ts"],"sourcesContent":["import { pathHasPrefix } from './path-has-prefix'\n\n/**\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n // If the path doesn't start with the prefix we can return it as is. This\n // protects us from situations where the prefix is a substring of the path\n // prefix such as:\n //\n // For prefix: /blog\n //\n // /blog -> true\n // /blog/ -> true\n // /blog/1 -> true\n // /blogging -> false\n // /blogging/ -> false\n // /blogging/1 -> false\n if (!pathHasPrefix(path, prefix)) {\n return path\n }\n\n // Remove the prefix from the path via slicing.\n const withoutPrefix = path.slice(prefix.length)\n\n // If the path without the prefix starts with a `/` we can return it as is.\n if (withoutPrefix.startsWith('/')) {\n return withoutPrefix\n }\n\n // If the path without the prefix doesn't start with a `/` we need to add it\n // back to the path to make sure it's a valid path.\n return `/${withoutPrefix}`\n}\n"],"names":["removePathPrefix","path","prefix","pathHasPrefix","withoutPrefix","slice","length","startsWith"],"mappings":";;;;+BAUgBA;;;eAAAA;;;+BAVc;AAUvB,SAASA,iBAAiBC,IAAY,EAAEC,MAAc;IAC3D,yEAAyE;IACzE,0EAA0E;IAC1E,kBAAkB;IAClB,EAAE;IACF,oBAAoB;IACpB,EAAE;IACF,kBAAkB;IAClB,mBAAmB;IACnB,oBAAoB;IACpB,uBAAuB;IACvB,wBAAwB;IACxB,yBAAyB;IACzB,IAAI,CAACC,IAAAA,4BAAa,EAACF,MAAMC,SAAS;QAChC,OAAOD;IACT;IAEA,+CAA+C;IAC/C,MAAMG,gBAAgBH,KAAKI,KAAK,CAACH,OAAOI,MAAM;IAE9C,2EAA2E;IAC3E,IAAIF,cAAcG,UAAU,CAAC,MAAM;QACjC,OAAOH;IACT;IAEA,4EAA4E;IAC5E,mDAAmD;IACnD,OAAO,CAAC,CAAC,EAAEA,eAAe;AAC5B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..faf097f726c8d4d96c6c56e3836700d12fcf5ee4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.d.ts @@ -0,0 +1,9 @@ +/** + * Removes the trailing slash for a given route or page path. Examples: + * - `/foo/bar/` -> `/foo/bar` + * - `/foo/bar` -> `/foo/bar` + * + * Uses charCodeAt (47 === '/') instead of regex to avoid the overhead of + * compiling and executing a RegExp on every call (~3-5x faster). + */ +export declare function removeTrailingSlash(route: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js new file mode 100644 index 0000000000000000000000000000000000000000..6d0f1334bf85e46d159b4b6541d99d5ab581716c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js @@ -0,0 +1,22 @@ +/** + * Removes the trailing slash for a given route or page path. Examples: + * - `/foo/bar/` -> `/foo/bar` + * - `/foo/bar` -> `/foo/bar` + * + * Uses charCodeAt (47 === '/') instead of regex to avoid the overhead of + * compiling and executing a RegExp on every call (~3-5x faster). + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "removeTrailingSlash", { + enumerable: true, + get: function() { + return removeTrailingSlash; + } +}); +function removeTrailingSlash(route) { + return route.charCodeAt(route.length - 1) === 47 && route.length > 1 ? route.slice(0, -1) : route; +} + +//# sourceMappingURL=remove-trailing-slash.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0d665fc9ee6898d99b23e877ccbfadc040f34c0e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/remove-trailing-slash.ts"],"sourcesContent":["/**\n * Removes the trailing slash for a given route or page path. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n *\n * Uses charCodeAt (47 === '/') instead of regex to avoid the overhead of\n * compiling and executing a RegExp on every call (~3-5x faster).\n */\nexport function removeTrailingSlash(route: string) {\n return route.charCodeAt(route.length - 1) === 47 && route.length > 1\n ? route.slice(0, -1)\n : route\n}\n"],"names":["removeTrailingSlash","route","charCodeAt","length","slice"],"mappings":"AAAA;;;;;;;CAOC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,oBAAoBC,KAAa;IAC/C,OAAOA,MAAMC,UAAU,CAACD,MAAME,MAAM,GAAG,OAAO,MAAMF,MAAME,MAAM,GAAG,IAC/DF,MAAMG,KAAK,CAAC,GAAG,CAAC,KAChBH;AACN","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a1e6bfaabcec211884f1f0e228b91d150783732 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.d.ts @@ -0,0 +1,17 @@ +import type { Params } from '../../../../server/request/params'; +import type { DynamicParamTypes } from '../../app-router-types'; +import type { NormalizedAppRoute } from '../routes/app'; +/** + * Resolves a route parameter value from the route segments at the given depth. + * This shared logic is used by both extractPathnameRouteParamSegmentsFromLoaderTree + * and resolveRouteParamsFromTree. + * + * @param paramName - The parameter name to resolve + * @param paramType - The parameter type (dynamic, catchall, etc.) + * @param depth - The current depth in the route tree + * @param route - The normalized route containing segments + * @param params - The current params object (used to resolve embedded param references) + * @param options - Configuration options + * @returns The resolved parameter value, or undefined if it cannot be resolved + */ +export declare function resolveParamValue(paramName: string, paramType: DynamicParamTypes, depth: number, route: NormalizedAppRoute, params: Params): string | string[] | undefined; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.js new file mode 100644 index 0000000000000000000000000000000000000000..0f4a7c7caf32e19fcbd1433e1479f3a6b813c01a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "resolveParamValue", { + enumerable: true, + get: function() { + return resolveParamValue; + } +}); +const _invarianterror = require("../../invariant-error"); +const _interceptionprefixfromparamtype = require("./interception-prefix-from-param-type"); +/** + * Extracts the param value from a path segment, handling interception markers + * based on the expected param type. + * + * @param pathSegment - The path segment to extract the value from + * @param params - The current params object for resolving dynamic param references + * @param paramType - The expected param type which may include interception marker info + * @returns The extracted param value + */ function getParamValueFromSegment(pathSegment, params, paramType) { + // If the segment is dynamic, resolve it from the params object + if (pathSegment.type === 'dynamic') { + return params[pathSegment.param.paramName]; + } + // If the paramType indicates this is an intercepted param, strip the marker + // that matches the interception marker in the param type + const interceptionPrefix = (0, _interceptionprefixfromparamtype.interceptionPrefixFromParamType)(paramType); + if (interceptionPrefix === pathSegment.interceptionMarker) { + return pathSegment.name.replace(pathSegment.interceptionMarker, ''); + } + // For static segments, use the name + return pathSegment.name; +} +function resolveParamValue(paramName, paramType, depth, route, params) { + switch(paramType){ + case 'catchall': + case 'optional-catchall': + case 'catchall-intercepted-(..)(..)': + case 'catchall-intercepted-(.)': + case 'catchall-intercepted-(..)': + case 'catchall-intercepted-(...)': + // For catchall routes, derive from pathname using depth to determine + // which segments to use + const processedSegments = []; + // Process segments to handle any embedded dynamic params + for(let index = depth; index < route.segments.length; index++){ + const pathSegment = route.segments[index]; + if (pathSegment.type === 'static') { + let value = pathSegment.name; + // For intercepted catch-all params, strip the marker from the first segment + const interceptionPrefix = (0, _interceptionprefixfromparamtype.interceptionPrefixFromParamType)(paramType); + if (interceptionPrefix && index === depth && interceptionPrefix === pathSegment.interceptionMarker) { + // Strip the interception marker from the value + value = value.replace(pathSegment.interceptionMarker, ''); + } + processedSegments.push(value); + } else { + // If the segment is a param placeholder, check if we have its value + if (!params.hasOwnProperty(pathSegment.param.paramName)) { + // If the segment is an optional catchall, we can break out of the + // loop because it's optional! + if (pathSegment.param.paramType === 'optional-catchall') { + break; + } + // Unknown param placeholder in pathname - can't derive full value + return undefined; + } + // If the segment matches a param, use the param value + // We don't encode values here as that's handled during retrieval. + const paramValue = params[pathSegment.param.paramName]; + if (Array.isArray(paramValue)) { + processedSegments.push(...paramValue); + } else { + processedSegments.push(paramValue); + } + } + } + if (processedSegments.length > 0) { + return processedSegments; + } else if (paramType === 'optional-catchall') { + return undefined; + } else { + // We shouldn't be able to match a catchall segment without any path + // segments if it's not an optional catchall + throw new _invarianterror.InvariantError(`Unexpected empty path segments match for a route "${route.pathname}" with param "${paramName}" of type "${paramType}"`); + } + case 'dynamic': + case 'dynamic-intercepted-(..)(..)': + case 'dynamic-intercepted-(.)': + case 'dynamic-intercepted-(..)': + case 'dynamic-intercepted-(...)': + // For regular dynamic parameters, take the segment at this depth + if (depth < route.segments.length) { + const pathSegment = route.segments[depth]; + // Check if the segment at this depth is a placeholder for an unknown param + if (pathSegment.type === 'dynamic' && !params.hasOwnProperty(pathSegment.param.paramName)) { + // The segment is a placeholder like [category] and we don't have the value + return undefined; + } + // If the segment matches a param, use the param value from params object + // Otherwise it's a static segment, just use it directly + // We don't encode values here as that's handled during retrieval + return getParamValueFromSegment(pathSegment, params, paramType); + } + return undefined; + default: + paramType; + } +} + +//# sourceMappingURL=resolve-param-value.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c651f237996d26979f4ecee56b9bef9ef57d8786 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-param-value.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/resolve-param-value.ts"],"sourcesContent":["import type { Params } from '../../../../server/request/params'\nimport type { DynamicParamTypes } from '../../app-router-types'\nimport { InvariantError } from '../../invariant-error'\nimport type {\n NormalizedAppRoute,\n NormalizedAppRouteSegment,\n} from '../routes/app'\nimport { interceptionPrefixFromParamType } from './interception-prefix-from-param-type'\n\n/**\n * Extracts the param value from a path segment, handling interception markers\n * based on the expected param type.\n *\n * @param pathSegment - The path segment to extract the value from\n * @param params - The current params object for resolving dynamic param references\n * @param paramType - The expected param type which may include interception marker info\n * @returns The extracted param value\n */\nfunction getParamValueFromSegment(\n pathSegment: NormalizedAppRouteSegment,\n params: Params,\n paramType: DynamicParamTypes\n): string {\n // If the segment is dynamic, resolve it from the params object\n if (pathSegment.type === 'dynamic') {\n return params[pathSegment.param.paramName] as string\n }\n\n // If the paramType indicates this is an intercepted param, strip the marker\n // that matches the interception marker in the param type\n const interceptionPrefix = interceptionPrefixFromParamType(paramType)\n if (interceptionPrefix === pathSegment.interceptionMarker) {\n return pathSegment.name.replace(pathSegment.interceptionMarker, '')\n }\n\n // For static segments, use the name\n return pathSegment.name\n}\n\n/**\n * Resolves a route parameter value from the route segments at the given depth.\n * This shared logic is used by both extractPathnameRouteParamSegmentsFromLoaderTree\n * and resolveRouteParamsFromTree.\n *\n * @param paramName - The parameter name to resolve\n * @param paramType - The parameter type (dynamic, catchall, etc.)\n * @param depth - The current depth in the route tree\n * @param route - The normalized route containing segments\n * @param params - The current params object (used to resolve embedded param references)\n * @param options - Configuration options\n * @returns The resolved parameter value, or undefined if it cannot be resolved\n */\nexport function resolveParamValue(\n paramName: string,\n paramType: DynamicParamTypes,\n depth: number,\n route: NormalizedAppRoute,\n params: Params\n): string | string[] | undefined {\n switch (paramType) {\n case 'catchall':\n case 'optional-catchall':\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n // For catchall routes, derive from pathname using depth to determine\n // which segments to use\n const processedSegments: string[] = []\n\n // Process segments to handle any embedded dynamic params\n for (let index = depth; index < route.segments.length; index++) {\n const pathSegment = route.segments[index]\n\n if (pathSegment.type === 'static') {\n let value = pathSegment.name\n\n // For intercepted catch-all params, strip the marker from the first segment\n const interceptionPrefix = interceptionPrefixFromParamType(paramType)\n if (\n interceptionPrefix &&\n index === depth &&\n interceptionPrefix === pathSegment.interceptionMarker\n ) {\n // Strip the interception marker from the value\n value = value.replace(pathSegment.interceptionMarker, '')\n }\n\n processedSegments.push(value)\n } else {\n // If the segment is a param placeholder, check if we have its value\n if (!params.hasOwnProperty(pathSegment.param.paramName)) {\n // If the segment is an optional catchall, we can break out of the\n // loop because it's optional!\n if (pathSegment.param.paramType === 'optional-catchall') {\n break\n }\n\n // Unknown param placeholder in pathname - can't derive full value\n return undefined\n }\n\n // If the segment matches a param, use the param value\n // We don't encode values here as that's handled during retrieval.\n const paramValue = params[pathSegment.param.paramName]\n if (Array.isArray(paramValue)) {\n processedSegments.push(...paramValue)\n } else {\n processedSegments.push(paramValue as string)\n }\n }\n }\n\n if (processedSegments.length > 0) {\n return processedSegments\n } else if (paramType === 'optional-catchall') {\n return undefined\n } else {\n // We shouldn't be able to match a catchall segment without any path\n // segments if it's not an optional catchall\n throw new InvariantError(\n `Unexpected empty path segments match for a route \"${route.pathname}\" with param \"${paramName}\" of type \"${paramType}\"`\n )\n }\n case 'dynamic':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)':\n // For regular dynamic parameters, take the segment at this depth\n if (depth < route.segments.length) {\n const pathSegment = route.segments[depth]\n\n // Check if the segment at this depth is a placeholder for an unknown param\n if (\n pathSegment.type === 'dynamic' &&\n !params.hasOwnProperty(pathSegment.param.paramName)\n ) {\n // The segment is a placeholder like [category] and we don't have the value\n return undefined\n }\n\n // If the segment matches a param, use the param value from params object\n // Otherwise it's a static segment, just use it directly\n // We don't encode values here as that's handled during retrieval\n return getParamValueFromSegment(pathSegment, params, paramType)\n }\n\n return undefined\n\n default:\n paramType satisfies never\n }\n}\n"],"names":["resolveParamValue","getParamValueFromSegment","pathSegment","params","paramType","type","param","paramName","interceptionPrefix","interceptionPrefixFromParamType","interceptionMarker","name","replace","depth","route","processedSegments","index","segments","length","value","push","hasOwnProperty","undefined","paramValue","Array","isArray","InvariantError","pathname"],"mappings":";;;;+BAoDgBA;;;eAAAA;;;gCAlDe;iDAKiB;AAEhD;;;;;;;;CAQC,GACD,SAASC,yBACPC,WAAsC,EACtCC,MAAc,EACdC,SAA4B;IAE5B,+DAA+D;IAC/D,IAAIF,YAAYG,IAAI,KAAK,WAAW;QAClC,OAAOF,MAAM,CAACD,YAAYI,KAAK,CAACC,SAAS,CAAC;IAC5C;IAEA,4EAA4E;IAC5E,yDAAyD;IACzD,MAAMC,qBAAqBC,IAAAA,gEAA+B,EAACL;IAC3D,IAAII,uBAAuBN,YAAYQ,kBAAkB,EAAE;QACzD,OAAOR,YAAYS,IAAI,CAACC,OAAO,CAACV,YAAYQ,kBAAkB,EAAE;IAClE;IAEA,oCAAoC;IACpC,OAAOR,YAAYS,IAAI;AACzB;AAeO,SAASX,kBACdO,SAAiB,EACjBH,SAA4B,EAC5BS,KAAa,EACbC,KAAyB,EACzBX,MAAc;IAEd,OAAQC;QACN,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,qEAAqE;YACrE,wBAAwB;YACxB,MAAMW,oBAA8B,EAAE;YAEtC,yDAAyD;YACzD,IAAK,IAAIC,QAAQH,OAAOG,QAAQF,MAAMG,QAAQ,CAACC,MAAM,EAAEF,QAAS;gBAC9D,MAAMd,cAAcY,MAAMG,QAAQ,CAACD,MAAM;gBAEzC,IAAId,YAAYG,IAAI,KAAK,UAAU;oBACjC,IAAIc,QAAQjB,YAAYS,IAAI;oBAE5B,4EAA4E;oBAC5E,MAAMH,qBAAqBC,IAAAA,gEAA+B,EAACL;oBAC3D,IACEI,sBACAQ,UAAUH,SACVL,uBAAuBN,YAAYQ,kBAAkB,EACrD;wBACA,+CAA+C;wBAC/CS,QAAQA,MAAMP,OAAO,CAACV,YAAYQ,kBAAkB,EAAE;oBACxD;oBAEAK,kBAAkBK,IAAI,CAACD;gBACzB,OAAO;oBACL,oEAAoE;oBACpE,IAAI,CAAChB,OAAOkB,cAAc,CAACnB,YAAYI,KAAK,CAACC,SAAS,GAAG;wBACvD,kEAAkE;wBAClE,8BAA8B;wBAC9B,IAAIL,YAAYI,KAAK,CAACF,SAAS,KAAK,qBAAqB;4BACvD;wBACF;wBAEA,kEAAkE;wBAClE,OAAOkB;oBACT;oBAEA,sDAAsD;oBACtD,kEAAkE;oBAClE,MAAMC,aAAapB,MAAM,CAACD,YAAYI,KAAK,CAACC,SAAS,CAAC;oBACtD,IAAIiB,MAAMC,OAAO,CAACF,aAAa;wBAC7BR,kBAAkBK,IAAI,IAAIG;oBAC5B,OAAO;wBACLR,kBAAkBK,IAAI,CAACG;oBACzB;gBACF;YACF;YAEA,IAAIR,kBAAkBG,MAAM,GAAG,GAAG;gBAChC,OAAOH;YACT,OAAO,IAAIX,cAAc,qBAAqB;gBAC5C,OAAOkB;YACT,OAAO;gBACL,oEAAoE;gBACpE,4CAA4C;gBAC5C,MAAM,IAAII,8BAAc,CACtB,CAAC,kDAAkD,EAAEZ,MAAMa,QAAQ,CAAC,cAAc,EAAEpB,UAAU,WAAW,EAAEH,UAAU,CAAC,CAAC;YAE3H;QACF,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,iEAAiE;YACjE,IAAIS,QAAQC,MAAMG,QAAQ,CAACC,MAAM,EAAE;gBACjC,MAAMhB,cAAcY,MAAMG,QAAQ,CAACJ,MAAM;gBAEzC,2EAA2E;gBAC3E,IACEX,YAAYG,IAAI,KAAK,aACrB,CAACF,OAAOkB,cAAc,CAACnB,YAAYI,KAAK,CAACC,SAAS,GAClD;oBACA,2EAA2E;oBAC3E,OAAOe;gBACT;gBAEA,yEAAyE;gBACzE,wDAAwD;gBACxD,iEAAiE;gBACjE,OAAOrB,yBAAyBC,aAAaC,QAAQC;YACvD;YAEA,OAAOkB;QAET;YACElB;IACJ;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..feacda65d795474fb16802bbb40c812eef7306cd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.d.ts @@ -0,0 +1,17 @@ +import type { ParsedUrlQuery } from 'querystring'; +import type { Rewrite } from '../../../../lib/load-custom-routes'; +import { type ParsedRelativeUrl } from './parse-relative-url'; +import type { ParsedUrl } from './parse-url'; +type ParsedAs = ParsedRelativeUrl | ParsedUrl; +export default function resolveRewrites(asPath: string, pages: string[], rewrites: { + beforeFiles: Rewrite[]; + afterFiles: Rewrite[]; + fallback: Rewrite[]; +}, query: ParsedUrlQuery, resolveHref: (path: string) => string, locales?: readonly string[]): { + matchedPage: boolean; + parsedAs: ParsedAs; + asPath: string; + resolvedHref?: string; + externalDest?: boolean; +}; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js new file mode 100644 index 0000000000000000000000000000000000000000..7198c4e67f6dc543534eaffd08528589aeafe089 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return resolveRewrites; + } +}); +const _pathmatch = require("./path-match"); +const _preparedestination = require("./prepare-destination"); +const _removetrailingslash = require("./remove-trailing-slash"); +const _normalizelocalepath = require("../../i18n/normalize-locale-path"); +const _removebasepath = require("../../../../client/remove-base-path"); +const _parserelativeurl = require("./parse-relative-url"); +function resolveRewrites(asPath, pages, rewrites, query, resolveHref, locales) { + let matchedPage = false; + let externalDest = false; + let parsedAs = (0, _parserelativeurl.parseRelativeUrl)(asPath); + let fsPathname = (0, _removetrailingslash.removeTrailingSlash)((0, _normalizelocalepath.normalizeLocalePath)((0, _removebasepath.removeBasePath)(parsedAs.pathname), locales).pathname); + let resolvedHref; + const handleRewrite = (rewrite)=>{ + const matcher = (0, _pathmatch.getPathMatch)(rewrite.source + (process.env.__NEXT_TRAILING_SLASH ? '(/)?' : ''), { + removeUnnamedParams: true, + strict: true + }); + let params = matcher(parsedAs.pathname); + if ((rewrite.has || rewrite.missing) && params) { + const hasParams = (0, _preparedestination.matchHas)({ + headers: { + host: document.location.hostname, + 'user-agent': navigator.userAgent + }, + cookies: document.cookie.split('; ').reduce((acc, item)=>{ + const [key, ...value] = item.split('='); + acc[key] = value.join('='); + return acc; + }, {}) + }, parsedAs.query, rewrite.has, rewrite.missing); + if (hasParams) { + Object.assign(params, hasParams); + } else { + params = false; + } + } + if (params) { + if (!rewrite.destination) { + // this is a proxied rewrite which isn't handled on the client + externalDest = true; + return true; + } + const destRes = (0, _preparedestination.prepareDestination)({ + appendParamsToQuery: true, + destination: rewrite.destination, + params: params, + query: query + }); + parsedAs = destRes.parsedDestination; + asPath = destRes.newUrl; + Object.assign(query, destRes.parsedDestination.query); + fsPathname = (0, _removetrailingslash.removeTrailingSlash)((0, _normalizelocalepath.normalizeLocalePath)((0, _removebasepath.removeBasePath)(asPath), locales).pathname); + if (pages.includes(fsPathname)) { + // check if we now match a page as this means we are done + // resolving the rewrites + matchedPage = true; + resolvedHref = fsPathname; + return true; + } + // check if we match a dynamic-route, if so we break the rewrites chain + resolvedHref = resolveHref(fsPathname); + if (resolvedHref !== asPath && pages.includes(resolvedHref)) { + matchedPage = true; + return true; + } + } + }; + let finished = false; + for(let i = 0; i < rewrites.beforeFiles.length; i++){ + // we don't end after match in beforeFiles to allow + // continuing through all beforeFiles rewrites + handleRewrite(rewrites.beforeFiles[i]); + } + matchedPage = pages.includes(fsPathname); + if (!matchedPage) { + if (!finished) { + for(let i = 0; i < rewrites.afterFiles.length; i++){ + if (handleRewrite(rewrites.afterFiles[i])) { + finished = true; + break; + } + } + } + // check dynamic route before processing fallback rewrites + if (!finished) { + resolvedHref = resolveHref(fsPathname); + matchedPage = pages.includes(resolvedHref); + finished = matchedPage; + } + if (!finished) { + for(let i = 0; i < rewrites.fallback.length; i++){ + if (handleRewrite(rewrites.fallback[i])) { + finished = true; + break; + } + } + } + } + return { + asPath, + parsedAs, + matchedPage, + resolvedHref, + externalDest + }; +} + +//# sourceMappingURL=resolve-rewrites.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js.map new file mode 100644 index 0000000000000000000000000000000000000000..19e8ae60384e69107946c7ca28b32af3c4275227 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/resolve-rewrites.ts"],"sourcesContent":["import type { ParsedUrlQuery } from 'querystring'\nimport type { Rewrite } from '../../../../lib/load-custom-routes'\nimport { getPathMatch } from './path-match'\nimport { matchHas, prepareDestination } from './prepare-destination'\nimport { removeTrailingSlash } from './remove-trailing-slash'\nimport { normalizeLocalePath } from '../../i18n/normalize-locale-path'\nimport { removeBasePath } from '../../../../client/remove-base-path'\nimport { parseRelativeUrl, type ParsedRelativeUrl } from './parse-relative-url'\nimport type { ParsedUrl } from './parse-url'\n\ntype ParsedAs = ParsedRelativeUrl | ParsedUrl\nexport default function resolveRewrites(\n asPath: string,\n pages: string[],\n rewrites: {\n beforeFiles: Rewrite[]\n afterFiles: Rewrite[]\n fallback: Rewrite[]\n },\n query: ParsedUrlQuery,\n resolveHref: (path: string) => string,\n locales?: readonly string[]\n): {\n matchedPage: boolean\n parsedAs: ParsedAs\n asPath: string\n resolvedHref?: string\n externalDest?: boolean\n} {\n let matchedPage = false\n let externalDest = false\n let parsedAs: ParsedAs = parseRelativeUrl(asPath)\n let fsPathname = removeTrailingSlash(\n normalizeLocalePath(removeBasePath(parsedAs.pathname), locales).pathname\n )\n let resolvedHref\n\n const handleRewrite = (rewrite: Rewrite) => {\n const matcher = getPathMatch(\n rewrite.source + (process.env.__NEXT_TRAILING_SLASH ? '(/)?' : ''),\n {\n removeUnnamedParams: true,\n strict: true,\n }\n )\n\n let params = matcher(parsedAs.pathname)\n\n if ((rewrite.has || rewrite.missing) && params) {\n const hasParams = matchHas(\n {\n headers: {\n host: document.location.hostname,\n 'user-agent': navigator.userAgent,\n },\n cookies: document.cookie\n .split('; ')\n .reduce>((acc, item) => {\n const [key, ...value] = item.split('=')\n acc[key] = value.join('=')\n return acc\n }, {}),\n } as any,\n parsedAs.query,\n rewrite.has,\n rewrite.missing\n )\n\n if (hasParams) {\n Object.assign(params, hasParams)\n } else {\n params = false\n }\n }\n\n if (params) {\n if (!rewrite.destination) {\n // this is a proxied rewrite which isn't handled on the client\n externalDest = true\n return true\n }\n const destRes = prepareDestination({\n appendParamsToQuery: true,\n destination: rewrite.destination,\n params: params,\n query: query,\n })\n parsedAs = destRes.parsedDestination\n asPath = destRes.newUrl\n Object.assign(query, destRes.parsedDestination.query)\n\n fsPathname = removeTrailingSlash(\n normalizeLocalePath(removeBasePath(asPath), locales).pathname\n )\n\n if (pages.includes(fsPathname)) {\n // check if we now match a page as this means we are done\n // resolving the rewrites\n matchedPage = true\n resolvedHref = fsPathname\n return true\n }\n\n // check if we match a dynamic-route, if so we break the rewrites chain\n resolvedHref = resolveHref(fsPathname)\n\n if (resolvedHref !== asPath && pages.includes(resolvedHref)) {\n matchedPage = true\n return true\n }\n }\n }\n let finished = false\n\n for (let i = 0; i < rewrites.beforeFiles.length; i++) {\n // we don't end after match in beforeFiles to allow\n // continuing through all beforeFiles rewrites\n handleRewrite(rewrites.beforeFiles[i])\n }\n matchedPage = pages.includes(fsPathname)\n\n if (!matchedPage) {\n if (!finished) {\n for (let i = 0; i < rewrites.afterFiles.length; i++) {\n if (handleRewrite(rewrites.afterFiles[i])) {\n finished = true\n break\n }\n }\n }\n\n // check dynamic route before processing fallback rewrites\n if (!finished) {\n resolvedHref = resolveHref(fsPathname)\n matchedPage = pages.includes(resolvedHref)\n finished = matchedPage\n }\n\n if (!finished) {\n for (let i = 0; i < rewrites.fallback.length; i++) {\n if (handleRewrite(rewrites.fallback[i])) {\n finished = true\n break\n }\n }\n }\n }\n\n return {\n asPath,\n parsedAs,\n matchedPage,\n resolvedHref,\n externalDest,\n }\n}\n"],"names":["resolveRewrites","asPath","pages","rewrites","query","resolveHref","locales","matchedPage","externalDest","parsedAs","parseRelativeUrl","fsPathname","removeTrailingSlash","normalizeLocalePath","removeBasePath","pathname","resolvedHref","handleRewrite","rewrite","matcher","getPathMatch","source","process","env","__NEXT_TRAILING_SLASH","removeUnnamedParams","strict","params","has","missing","hasParams","matchHas","headers","host","document","location","hostname","navigator","userAgent","cookies","cookie","split","reduce","acc","item","key","value","join","Object","assign","destination","destRes","prepareDestination","appendParamsToQuery","parsedDestination","newUrl","includes","finished","i","beforeFiles","length","afterFiles","fallback"],"mappings":";;;;+BAWA;;;eAAwBA;;;2BATK;oCACgB;qCACT;qCACA;gCACL;kCAC0B;AAI1C,SAASA,gBACtBC,MAAc,EACdC,KAAe,EACfC,QAIC,EACDC,KAAqB,EACrBC,WAAqC,EACrCC,OAA2B;IAQ3B,IAAIC,cAAc;IAClB,IAAIC,eAAe;IACnB,IAAIC,WAAqBC,IAAAA,kCAAgB,EAACT;IAC1C,IAAIU,aAAaC,IAAAA,wCAAmB,EAClCC,IAAAA,wCAAmB,EAACC,IAAAA,8BAAc,EAACL,SAASM,QAAQ,GAAGT,SAASS,QAAQ;IAE1E,IAAIC;IAEJ,MAAMC,gBAAgB,CAACC;QACrB,MAAMC,UAAUC,IAAAA,uBAAY,EAC1BF,QAAQG,MAAM,GAAIC,CAAAA,QAAQC,GAAG,CAACC,qBAAqB,GAAG,SAAS,EAAC,GAChE;YACEC,qBAAqB;YACrBC,QAAQ;QACV;QAGF,IAAIC,SAASR,QAAQV,SAASM,QAAQ;QAEtC,IAAI,AAACG,CAAAA,QAAQU,GAAG,IAAIV,QAAQW,OAAO,AAAD,KAAMF,QAAQ;YAC9C,MAAMG,YAAYC,IAAAA,4BAAQ,EACxB;gBACEC,SAAS;oBACPC,MAAMC,SAASC,QAAQ,CAACC,QAAQ;oBAChC,cAAcC,UAAUC,SAAS;gBACnC;gBACAC,SAASL,SAASM,MAAM,CACrBC,KAAK,CAAC,MACNC,MAAM,CAAyB,CAACC,KAAKC;oBACpC,MAAM,CAACC,KAAK,GAAGC,MAAM,GAAGF,KAAKH,KAAK,CAAC;oBACnCE,GAAG,CAACE,IAAI,GAAGC,MAAMC,IAAI,CAAC;oBACtB,OAAOJ;gBACT,GAAG,CAAC;YACR,GACAlC,SAASL,KAAK,EACdc,QAAQU,GAAG,EACXV,QAAQW,OAAO;YAGjB,IAAIC,WAAW;gBACbkB,OAAOC,MAAM,CAACtB,QAAQG;YACxB,OAAO;gBACLH,SAAS;YACX;QACF;QAEA,IAAIA,QAAQ;YACV,IAAI,CAACT,QAAQgC,WAAW,EAAE;gBACxB,8DAA8D;gBAC9D1C,eAAe;gBACf,OAAO;YACT;YACA,MAAM2C,UAAUC,IAAAA,sCAAkB,EAAC;gBACjCC,qBAAqB;gBACrBH,aAAahC,QAAQgC,WAAW;gBAChCvB,QAAQA;gBACRvB,OAAOA;YACT;YACAK,WAAW0C,QAAQG,iBAAiB;YACpCrD,SAASkD,QAAQI,MAAM;YACvBP,OAAOC,MAAM,CAAC7C,OAAO+C,QAAQG,iBAAiB,CAAClD,KAAK;YAEpDO,aAAaC,IAAAA,wCAAmB,EAC9BC,IAAAA,wCAAmB,EAACC,IAAAA,8BAAc,EAACb,SAASK,SAASS,QAAQ;YAG/D,IAAIb,MAAMsD,QAAQ,CAAC7C,aAAa;gBAC9B,yDAAyD;gBACzD,yBAAyB;gBACzBJ,cAAc;gBACdS,eAAeL;gBACf,OAAO;YACT;YAEA,uEAAuE;YACvEK,eAAeX,YAAYM;YAE3B,IAAIK,iBAAiBf,UAAUC,MAAMsD,QAAQ,CAACxC,eAAe;gBAC3DT,cAAc;gBACd,OAAO;YACT;QACF;IACF;IACA,IAAIkD,WAAW;IAEf,IAAK,IAAIC,IAAI,GAAGA,IAAIvD,SAASwD,WAAW,CAACC,MAAM,EAAEF,IAAK;QACpD,mDAAmD;QACnD,8CAA8C;QAC9CzC,cAAcd,SAASwD,WAAW,CAACD,EAAE;IACvC;IACAnD,cAAcL,MAAMsD,QAAQ,CAAC7C;IAE7B,IAAI,CAACJ,aAAa;QAChB,IAAI,CAACkD,UAAU;YACb,IAAK,IAAIC,IAAI,GAAGA,IAAIvD,SAAS0D,UAAU,CAACD,MAAM,EAAEF,IAAK;gBACnD,IAAIzC,cAAcd,SAAS0D,UAAU,CAACH,EAAE,GAAG;oBACzCD,WAAW;oBACX;gBACF;YACF;QACF;QAEA,0DAA0D;QAC1D,IAAI,CAACA,UAAU;YACbzC,eAAeX,YAAYM;YAC3BJ,cAAcL,MAAMsD,QAAQ,CAACxC;YAC7ByC,WAAWlD;QACb;QAEA,IAAI,CAACkD,UAAU;YACb,IAAK,IAAIC,IAAI,GAAGA,IAAIvD,SAAS2D,QAAQ,CAACF,MAAM,EAAEF,IAAK;gBACjD,IAAIzC,cAAcd,SAAS2D,QAAQ,CAACJ,EAAE,GAAG;oBACvCD,WAAW;oBACX;gBACF;YACF;QACF;IACF;IAEA,OAAO;QACLxD;QACAQ;QACAF;QACAS;QACAR;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..89a1e8fa4c862aad657109923c7a21e053eeefb2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.d.ts @@ -0,0 +1,28 @@ +/** + * Client-safe utilities for route matching that don't import server-side + * utilities to avoid bundling issues with Turbopack + */ +import type { Key, TokensToRegexpOptions, ParseOptions, TokensToFunctionOptions } from 'next/dist/compiled/path-to-regexp'; +/** + * Client-safe wrapper around pathToRegexp that handles path-to-regexp 6.3.0+ validation errors. + * This includes both "Can not repeat without prefix/suffix" and "Must have text between parameters" errors. + */ +export declare function safePathToRegexp(route: string | RegExp | Array, keys?: Key[], options?: TokensToRegexpOptions & ParseOptions): RegExp; +/** + * Client-safe wrapper around compile that handles path-to-regexp 6.3.0+ validation errors. + * No server-side error reporting to avoid bundling issues. + * When normalization is applied, the returned compiler function automatically strips + * the internal separator from the output URL. + */ +export declare function safeCompile(route: string, options?: TokensToFunctionOptions & ParseOptions): import("path-to-regexp").PathFunction; +/** + * Client-safe wrapper around regexpToFunction that automatically cleans parameters. + */ +export declare function safeRegexpToFunction = Record>(regexp: RegExp, keys?: Key[]): (pathname: string) => { + params: T; +} | false; +/** + * Safe wrapper for route matcher functions that automatically cleans parameters. + * This is client-safe and doesn't import path-to-regexp. + */ +export declare function safeRouteMatcher>(matcherFn: (pathname: string) => false | T): (pathname: string) => false | T; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..b04f744c6b84c6a5a4b72a60bf3a82681d25fd1f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.js @@ -0,0 +1,113 @@ +/** + * Client-safe utilities for route matching that don't import server-side + * utilities to avoid bundling issues with Turbopack + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + safeCompile: null, + safePathToRegexp: null, + safeRegexpToFunction: null, + safeRouteMatcher: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + safeCompile: function() { + return safeCompile; + }, + safePathToRegexp: function() { + return safePathToRegexp; + }, + safeRegexpToFunction: function() { + return safeRegexpToFunction; + }, + safeRouteMatcher: function() { + return safeRouteMatcher; + } +}); +const _pathtoregexp = require("next/dist/compiled/path-to-regexp"); +const _routepatternnormalizer = require("../../../../lib/route-pattern-normalizer"); +function safePathToRegexp(route, keys, options) { + if (typeof route !== 'string') { + return (0, _pathtoregexp.pathToRegexp)(route, keys, options); + } + // Check if normalization is needed and cache the result + const needsNormalization = (0, _routepatternnormalizer.hasAdjacentParameterIssues)(route); + const routeToUse = needsNormalization ? (0, _routepatternnormalizer.normalizeAdjacentParameters)(route) : route; + try { + return (0, _pathtoregexp.pathToRegexp)(routeToUse, keys, options); + } catch (error) { + // Only try normalization if we haven't already normalized + if (!needsNormalization) { + try { + const normalizedRoute = (0, _routepatternnormalizer.normalizeAdjacentParameters)(route); + return (0, _pathtoregexp.pathToRegexp)(normalizedRoute, keys, options); + } catch (retryError) { + // If that doesn't work, fall back to original error + throw error; + } + } + throw error; + } +} +function safeCompile(route, options) { + // Check if normalization is needed and cache the result + const needsNormalization = (0, _routepatternnormalizer.hasAdjacentParameterIssues)(route); + const routeToUse = needsNormalization ? (0, _routepatternnormalizer.normalizeAdjacentParameters)(route) : route; + try { + const compiler = (0, _pathtoregexp.compile)(routeToUse, options); + // If we normalized the route, wrap the compiler to strip separators from output + // The normalization inserts _NEXTSEP_ as a literal string in the pattern to satisfy + // path-to-regexp validation, but we don't want it in the final compiled URL + if (needsNormalization) { + return (params)=>{ + return (0, _routepatternnormalizer.stripNormalizedSeparators)(compiler(params)); + }; + } + return compiler; + } catch (error) { + // Only try normalization if we haven't already normalized + if (!needsNormalization) { + try { + const normalizedRoute = (0, _routepatternnormalizer.normalizeAdjacentParameters)(route); + const compiler = (0, _pathtoregexp.compile)(normalizedRoute, options); + // Wrap the compiler to strip separators from output + return (params)=>{ + return (0, _routepatternnormalizer.stripNormalizedSeparators)(compiler(params)); + }; + } catch (retryError) { + // If that doesn't work, fall back to original error + throw error; + } + } + throw error; + } +} +function safeRegexpToFunction(regexp, keys) { + const originalMatcher = (0, _pathtoregexp.regexpToFunction)(regexp, keys || []); + return (pathname)=>{ + const result = originalMatcher(pathname); + if (!result) return false; + // Clean parameters before returning + return { + ...result, + params: (0, _routepatternnormalizer.stripParameterSeparators)(result.params) + }; + }; +} +function safeRouteMatcher(matcherFn) { + return (pathname)=>{ + const result = matcherFn(pathname); + if (!result) return false; + // Clean parameters before returning + return (0, _routepatternnormalizer.stripParameterSeparators)(result); + }; +} + +//# sourceMappingURL=route-match-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8f12d5bacc335548df09c4e848dbae96a1aaee31 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-match-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/route-match-utils.ts"],"sourcesContent":["/**\n * Client-safe utilities for route matching that don't import server-side\n * utilities to avoid bundling issues with Turbopack\n */\n\nimport type {\n Key,\n TokensToRegexpOptions,\n ParseOptions,\n TokensToFunctionOptions,\n} from 'next/dist/compiled/path-to-regexp'\nimport {\n pathToRegexp,\n compile,\n regexpToFunction,\n} from 'next/dist/compiled/path-to-regexp'\nimport {\n hasAdjacentParameterIssues,\n normalizeAdjacentParameters,\n stripParameterSeparators,\n stripNormalizedSeparators,\n} from '../../../../lib/route-pattern-normalizer'\n\n/**\n * Client-safe wrapper around pathToRegexp that handles path-to-regexp 6.3.0+ validation errors.\n * This includes both \"Can not repeat without prefix/suffix\" and \"Must have text between parameters\" errors.\n */\nexport function safePathToRegexp(\n route: string | RegExp | Array,\n keys?: Key[],\n options?: TokensToRegexpOptions & ParseOptions\n): RegExp {\n if (typeof route !== 'string') {\n return pathToRegexp(route, keys, options)\n }\n\n // Check if normalization is needed and cache the result\n const needsNormalization = hasAdjacentParameterIssues(route)\n const routeToUse = needsNormalization\n ? normalizeAdjacentParameters(route)\n : route\n\n try {\n return pathToRegexp(routeToUse, keys, options)\n } catch (error) {\n // Only try normalization if we haven't already normalized\n if (!needsNormalization) {\n try {\n const normalizedRoute = normalizeAdjacentParameters(route)\n return pathToRegexp(normalizedRoute, keys, options)\n } catch (retryError) {\n // If that doesn't work, fall back to original error\n throw error\n }\n }\n throw error\n }\n}\n\n/**\n * Client-safe wrapper around compile that handles path-to-regexp 6.3.0+ validation errors.\n * No server-side error reporting to avoid bundling issues.\n * When normalization is applied, the returned compiler function automatically strips\n * the internal separator from the output URL.\n */\nexport function safeCompile(\n route: string,\n options?: TokensToFunctionOptions & ParseOptions\n) {\n // Check if normalization is needed and cache the result\n const needsNormalization = hasAdjacentParameterIssues(route)\n const routeToUse = needsNormalization\n ? normalizeAdjacentParameters(route)\n : route\n\n try {\n const compiler = compile(routeToUse, options)\n\n // If we normalized the route, wrap the compiler to strip separators from output\n // The normalization inserts _NEXTSEP_ as a literal string in the pattern to satisfy\n // path-to-regexp validation, but we don't want it in the final compiled URL\n if (needsNormalization) {\n return (params: any) => {\n return stripNormalizedSeparators(compiler(params))\n }\n }\n\n return compiler\n } catch (error) {\n // Only try normalization if we haven't already normalized\n if (!needsNormalization) {\n try {\n const normalizedRoute = normalizeAdjacentParameters(route)\n const compiler = compile(normalizedRoute, options)\n\n // Wrap the compiler to strip separators from output\n return (params: any) => {\n return stripNormalizedSeparators(compiler(params))\n }\n } catch (retryError) {\n // If that doesn't work, fall back to original error\n throw error\n }\n }\n throw error\n }\n}\n\n/**\n * Client-safe wrapper around regexpToFunction that automatically cleans parameters.\n */\nexport function safeRegexpToFunction<\n T extends Record = Record,\n>(regexp: RegExp, keys?: Key[]): (pathname: string) => { params: T } | false {\n const originalMatcher = regexpToFunction(regexp, keys || [])\n\n return (pathname: string) => {\n const result = originalMatcher(pathname)\n if (!result) return false\n\n // Clean parameters before returning\n return {\n ...result,\n params: stripParameterSeparators(result.params as any) as T,\n }\n }\n}\n\n/**\n * Safe wrapper for route matcher functions that automatically cleans parameters.\n * This is client-safe and doesn't import path-to-regexp.\n */\nexport function safeRouteMatcher>(\n matcherFn: (pathname: string) => false | T\n): (pathname: string) => false | T {\n return (pathname: string) => {\n const result = matcherFn(pathname)\n if (!result) return false\n\n // Clean parameters before returning\n return stripParameterSeparators(result) as T\n }\n}\n"],"names":["safeCompile","safePathToRegexp","safeRegexpToFunction","safeRouteMatcher","route","keys","options","pathToRegexp","needsNormalization","hasAdjacentParameterIssues","routeToUse","normalizeAdjacentParameters","error","normalizedRoute","retryError","compiler","compile","params","stripNormalizedSeparators","regexp","originalMatcher","regexpToFunction","pathname","result","stripParameterSeparators","matcherFn"],"mappings":"AAAA;;;CAGC;;;;;;;;;;;;;;;;;IA8DeA,WAAW;eAAXA;;IAtCAC,gBAAgB;eAAhBA;;IAoFAC,oBAAoB;eAApBA;;IAqBAC,gBAAgB;eAAhBA;;;8BArHT;wCAMA;AAMA,SAASF,iBACdG,KAA+C,EAC/CC,IAAY,EACZC,OAA8C;IAE9C,IAAI,OAAOF,UAAU,UAAU;QAC7B,OAAOG,IAAAA,0BAAY,EAACH,OAAOC,MAAMC;IACnC;IAEA,wDAAwD;IACxD,MAAME,qBAAqBC,IAAAA,kDAA0B,EAACL;IACtD,MAAMM,aAAaF,qBACfG,IAAAA,mDAA2B,EAACP,SAC5BA;IAEJ,IAAI;QACF,OAAOG,IAAAA,0BAAY,EAACG,YAAYL,MAAMC;IACxC,EAAE,OAAOM,OAAO;QACd,0DAA0D;QAC1D,IAAI,CAACJ,oBAAoB;YACvB,IAAI;gBACF,MAAMK,kBAAkBF,IAAAA,mDAA2B,EAACP;gBACpD,OAAOG,IAAAA,0BAAY,EAACM,iBAAiBR,MAAMC;YAC7C,EAAE,OAAOQ,YAAY;gBACnB,oDAAoD;gBACpD,MAAMF;YACR;QACF;QACA,MAAMA;IACR;AACF;AAQO,SAASZ,YACdI,KAAa,EACbE,OAAgD;IAEhD,wDAAwD;IACxD,MAAME,qBAAqBC,IAAAA,kDAA0B,EAACL;IACtD,MAAMM,aAAaF,qBACfG,IAAAA,mDAA2B,EAACP,SAC5BA;IAEJ,IAAI;QACF,MAAMW,WAAWC,IAAAA,qBAAO,EAACN,YAAYJ;QAErC,gFAAgF;QAChF,oFAAoF;QACpF,4EAA4E;QAC5E,IAAIE,oBAAoB;YACtB,OAAO,CAACS;gBACN,OAAOC,IAAAA,iDAAyB,EAACH,SAASE;YAC5C;QACF;QAEA,OAAOF;IACT,EAAE,OAAOH,OAAO;QACd,0DAA0D;QAC1D,IAAI,CAACJ,oBAAoB;YACvB,IAAI;gBACF,MAAMK,kBAAkBF,IAAAA,mDAA2B,EAACP;gBACpD,MAAMW,WAAWC,IAAAA,qBAAO,EAACH,iBAAiBP;gBAE1C,oDAAoD;gBACpD,OAAO,CAACW;oBACN,OAAOC,IAAAA,iDAAyB,EAACH,SAASE;gBAC5C;YACF,EAAE,OAAOH,YAAY;gBACnB,oDAAoD;gBACpD,MAAMF;YACR;QACF;QACA,MAAMA;IACR;AACF;AAKO,SAASV,qBAEdiB,MAAc,EAAEd,IAAY;IAC5B,MAAMe,kBAAkBC,IAAAA,8BAAgB,EAAIF,QAAQd,QAAQ,EAAE;IAE9D,OAAO,CAACiB;QACN,MAAMC,SAASH,gBAAgBE;QAC/B,IAAI,CAACC,QAAQ,OAAO;QAEpB,oCAAoC;QACpC,OAAO;YACL,GAAGA,MAAM;YACTN,QAAQO,IAAAA,gDAAwB,EAACD,OAAON,MAAM;QAChD;IACF;AACF;AAMO,SAASd,iBACdsB,SAA0C;IAE1C,OAAO,CAACH;QACN,MAAMC,SAASE,UAAUH;QACzB,IAAI,CAACC,QAAQ,OAAO;QAEpB,oCAAoC;QACpC,OAAOC,IAAAA,gDAAwB,EAACD;IAClC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2919d5e11730e9882821e5b721b40ecccbdc05c9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.d.ts @@ -0,0 +1,11 @@ +import type { Group } from './route-regex'; +import type { Params } from '../../../../server/request/params'; +export interface RouteMatchFn { + (pathname: string): false | Params; +} +type RouteMatcherOptions = { + re: Pick; + groups: Record; +}; +export declare function getRouteMatcher({ re, groups, }: RouteMatcherOptions): RouteMatchFn; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.js new file mode 100644 index 0000000000000000000000000000000000000000..67b6578068cb2bc4de9b08017cdcf7449252efc4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getRouteMatcher", { + enumerable: true, + get: function() { + return getRouteMatcher; + } +}); +const _utils = require("../../utils"); +const _routematchutils = require("./route-match-utils"); +function getRouteMatcher({ re, groups }) { + const rawMatcher = (pathname)=>{ + const routeMatch = re.exec(pathname); + if (!routeMatch) return false; + const decode = (param)=>{ + try { + return decodeURIComponent(param); + } catch { + throw new _utils.DecodeError('failed to decode param'); + } + }; + const params = {}; + for (const [key, group] of Object.entries(groups)){ + const match = routeMatch[group.pos]; + if (match !== undefined) { + if (group.repeat) { + params[key] = match.split('/').map((entry)=>decode(entry)); + } else { + params[key] = decode(match); + } + } + } + return params; + }; + // Wrap with safe matcher to handle parameter cleaning + return (0, _routematchutils.safeRouteMatcher)(rawMatcher); +} + +//# sourceMappingURL=route-matcher.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.js.map new file mode 100644 index 0000000000000000000000000000000000000000..97619ba18998580dccd2636c282bb268d3d5d1c9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-matcher.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/route-matcher.ts"],"sourcesContent":["import type { Group } from './route-regex'\nimport { DecodeError } from '../../utils'\nimport type { Params } from '../../../../server/request/params'\nimport { safeRouteMatcher } from './route-match-utils'\n\nexport interface RouteMatchFn {\n (pathname: string): false | Params\n}\n\ntype RouteMatcherOptions = {\n // We only use the exec method of the RegExp object. This helps us avoid using\n // type assertions that the passed in properties are of the correct type.\n re: Pick\n groups: Record\n}\n\nexport function getRouteMatcher({\n re,\n groups,\n}: RouteMatcherOptions): RouteMatchFn {\n const rawMatcher = (pathname: string) => {\n const routeMatch = re.exec(pathname)\n if (!routeMatch) return false\n\n const decode = (param: string) => {\n try {\n return decodeURIComponent(param)\n } catch {\n throw new DecodeError('failed to decode param')\n }\n }\n\n const params: Params = {}\n for (const [key, group] of Object.entries(groups)) {\n const match = routeMatch[group.pos]\n if (match !== undefined) {\n if (group.repeat) {\n params[key] = match.split('/').map((entry) => decode(entry))\n } else {\n params[key] = decode(match)\n }\n }\n }\n\n return params\n }\n\n // Wrap with safe matcher to handle parameter cleaning\n return safeRouteMatcher(rawMatcher)\n}\n"],"names":["getRouteMatcher","re","groups","rawMatcher","pathname","routeMatch","exec","decode","param","decodeURIComponent","DecodeError","params","key","group","Object","entries","match","pos","undefined","repeat","split","map","entry","safeRouteMatcher"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;uBAfY;iCAEK;AAa1B,SAASA,gBAAgB,EAC9BC,EAAE,EACFC,MAAM,EACc;IACpB,MAAMC,aAAa,CAACC;QAClB,MAAMC,aAAaJ,GAAGK,IAAI,CAACF;QAC3B,IAAI,CAACC,YAAY,OAAO;QAExB,MAAME,SAAS,CAACC;YACd,IAAI;gBACF,OAAOC,mBAAmBD;YAC5B,EAAE,OAAM;gBACN,MAAM,IAAIE,kBAAW,CAAC;YACxB;QACF;QAEA,MAAMC,SAAiB,CAAC;QACxB,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACb,QAAS;YACjD,MAAMc,QAAQX,UAAU,CAACQ,MAAMI,GAAG,CAAC;YACnC,IAAID,UAAUE,WAAW;gBACvB,IAAIL,MAAMM,MAAM,EAAE;oBAChBR,MAAM,CAACC,IAAI,GAAGI,MAAMI,KAAK,CAAC,KAAKC,GAAG,CAAC,CAACC,QAAUf,OAAOe;gBACvD,OAAO;oBACLX,MAAM,CAACC,IAAI,GAAGL,OAAOS;gBACvB;YACF;QACF;QAEA,OAAOL;IACT;IAEA,sDAAsD;IACtD,OAAOY,IAAAA,iCAAgB,EAACpB;AAC1B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7ac4f0d2314cfda404a32a2d2f1bce70ef1fb10 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.d.ts @@ -0,0 +1,109 @@ +export interface Group { + pos: number; + repeat: boolean; + optional: boolean; +} +export interface RouteRegex { + groups: { + [groupName: string]: Group; + }; + re: RegExp; +} +export type RegexReference = { + names: Record; + intercepted: Record; +}; +type GetNamedRouteRegexOptions = { + /** + * Whether to prefix the route keys with the NEXT_INTERCEPTION_MARKER_PREFIX + * or NEXT_QUERY_PARAM_PREFIX. This is only relevant when creating the + * routes-manifest during the build. + */ + prefixRouteKeys: boolean; + /** + * Whether to include the suffix in the route regex. This means that when you + * have something like `/[...slug].json` the `.json` part will be included + * in the regex, yielding `/(.*).json` as the regex. + */ + includeSuffix?: boolean; + /** + * Whether to include the prefix in the route regex. This means that when you + * have something like `/[...slug].json` the `/` part will be included + * in the regex, yielding `^/(.*).json$` as the regex. + * + * Note that interception markers will already be included without the need + */ + includePrefix?: boolean; + /** + * Whether to exclude the optional trailing slash from the route regex. + */ + excludeOptionalTrailingSlash?: boolean; + /** + * Whether to backtrack duplicate keys. This is only relevant when creating + * the routes-manifest during the build. + */ + backreferenceDuplicateKeys?: boolean; + /** + * If provided, this will be used as the reference for the dynamic parameter + * keys instead of generating them in context. This is currently only used for + * interception routes. + */ + reference?: RegexReference; +}; +type GetRouteRegexOptions = { + /** + * Whether to include extra parts in the route regex. This means that when you + * have something like `/[...slug].json` the `.json` part will be included + * in the regex, yielding `/(.*).json` as the regex. + */ + includeSuffix?: boolean; + /** + * Whether to include the prefix in the route regex. This means that when you + * have something like `/[...slug].json` the `/` part will be included + * in the regex, yielding `^/(.*).json$` as the regex. + * + * Note that interception markers will already be included without the need + * of adding this option. + */ + includePrefix?: boolean; + /** + * Whether to exclude the optional trailing slash from the route regex. + */ + excludeOptionalTrailingSlash?: boolean; +}; +/** + * From a normalized route this function generates a regular expression and + * a corresponding groups object intended to be used to store matching groups + * from the regular expression. + */ +export declare function getRouteRegex(normalizedRoute: string, { includeSuffix, includePrefix, excludeOptionalTrailingSlash, }?: GetRouteRegexOptions): RouteRegex; +/** + * This function extends `getRouteRegex` generating also a named regexp where + * each group is named along with a routeKeys object that indexes the assigned + * named group with its corresponding key. When the routeKeys need to be + * prefixed to uniquely identify internally the "prefixRouteKey" arg should + * be "true" currently this is only the case when creating the routes-manifest + * during the build + */ +export declare function getNamedRouteRegex(normalizedRoute: string, options: GetNamedRouteRegexOptions): { + namedRegex: string; + routeKeys: { + [named: string]: string; + }; + pathToRegexpPattern: string; + reference: RegexReference; + groups: { + [groupName: string]: Group; + }; + re: RegExp; +}; +/** + * Generates a named regexp. + * This is intended to be using for build time only. + */ +export declare function getNamedMiddlewareRegex(normalizedRoute: string, options: { + catchAll?: boolean; +}): { + namedRegex: string; +}; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.js new file mode 100644 index 0000000000000000000000000000000000000000..174032efe292c6df5aa50020d750aa96269a3262 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.js @@ -0,0 +1,256 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getNamedMiddlewareRegex: null, + getNamedRouteRegex: null, + getRouteRegex: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getNamedMiddlewareRegex: function() { + return getNamedMiddlewareRegex; + }, + getNamedRouteRegex: function() { + return getNamedRouteRegex; + }, + getRouteRegex: function() { + return getRouteRegex; + } +}); +const _constants = require("../../../../lib/constants"); +const _interceptionroutes = require("./interception-routes"); +const _escaperegexp = require("../../escape-regexp"); +const _removetrailingslash = require("./remove-trailing-slash"); +const _getdynamicparam = require("./get-dynamic-param"); +function getParametrizedRoute(route, includeSuffix, includePrefix) { + const groups = {}; + let groupIndex = 1; + const segments = []; + for (const segment of (0, _removetrailingslash.removeTrailingSlash)(route).slice(1).split('/')){ + const markerMatch = _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m)); + const paramMatches = segment.match(_getdynamicparam.PARAMETER_PATTERN) // Check for parameters + ; + if (markerMatch && paramMatches && paramMatches[2]) { + const { key, optional, repeat } = (0, _getdynamicparam.parseMatchedParameter)(paramMatches[2]); + groups[key] = { + pos: groupIndex++, + repeat, + optional + }; + segments.push(`/${(0, _escaperegexp.escapeStringRegexp)(markerMatch)}([^/]+?)`); + } else if (paramMatches && paramMatches[2]) { + const { key, repeat, optional } = (0, _getdynamicparam.parseMatchedParameter)(paramMatches[2]); + groups[key] = { + pos: groupIndex++, + repeat, + optional + }; + if (includePrefix && paramMatches[1]) { + segments.push(`/${(0, _escaperegexp.escapeStringRegexp)(paramMatches[1])}`); + } + let s = repeat ? optional ? '(?:/(.+?))?' : '/(.+?)' : '/([^/]+?)'; + // Remove the leading slash if includePrefix already added it. + if (includePrefix && paramMatches[1]) { + s = s.substring(1); + } + segments.push(s); + } else { + segments.push(`/${(0, _escaperegexp.escapeStringRegexp)(segment)}`); + } + // If there's a suffix, add it to the segments if it's enabled. + if (includeSuffix && paramMatches && paramMatches[3]) { + segments.push((0, _escaperegexp.escapeStringRegexp)(paramMatches[3])); + } + } + return { + parameterizedRoute: segments.join(''), + groups + }; +} +function getRouteRegex(normalizedRoute, { includeSuffix = false, includePrefix = false, excludeOptionalTrailingSlash = false } = {}) { + const { parameterizedRoute, groups } = getParametrizedRoute(normalizedRoute, includeSuffix, includePrefix); + let re = parameterizedRoute; + if (!excludeOptionalTrailingSlash) { + re += '(?:/)?'; + } + return { + re: new RegExp(`^${re}$`), + groups: groups + }; +} +/** + * Builds a function to generate a minimal routeKey using only a-z and minimal + * number of characters. + */ function buildGetSafeRouteKey() { + let i = 0; + return ()=>{ + let routeKey = ''; + let j = ++i; + while(j > 0){ + routeKey += String.fromCharCode(97 + (j - 1) % 26); + j = Math.floor((j - 1) / 26); + } + return routeKey; + }; +} +function getSafeKeyFromSegment({ interceptionMarker, getSafeRouteKey, segment, routeKeys, keyPrefix, backreferenceDuplicateKeys }) { + const { key, optional, repeat } = (0, _getdynamicparam.parseMatchedParameter)(segment); + // replace any non-word characters since they can break + // the named regex + let cleanedKey = key.replace(/\W/g, ''); + if (keyPrefix) { + cleanedKey = `${keyPrefix}${cleanedKey}`; + } + let invalidKey = false; + // check if the key is still invalid and fallback to using a known + // safe key + if (cleanedKey.length === 0 || cleanedKey.length > 30) { + invalidKey = true; + } + if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) { + invalidKey = true; + } + if (invalidKey) { + cleanedKey = getSafeRouteKey(); + } + const duplicateKey = cleanedKey in routeKeys; + if (keyPrefix) { + routeKeys[cleanedKey] = `${keyPrefix}${key}`; + } else { + routeKeys[cleanedKey] = key; + } + // if the segment has an interception marker, make sure that's part of the regex pattern + // this is to ensure that the route with the interception marker doesn't incorrectly match + // the non-intercepted route (ie /app/(.)[username] should not match /app/[username]) + const interceptionPrefix = interceptionMarker ? (0, _escaperegexp.escapeStringRegexp)(interceptionMarker) : ''; + let pattern; + if (duplicateKey && backreferenceDuplicateKeys) { + // Use a backreference to the key to ensure that the key is the same value + // in each of the placeholders. + pattern = `\\k<${cleanedKey}>`; + } else if (repeat) { + pattern = `(?<${cleanedKey}>.+?)`; + } else { + pattern = `(?<${cleanedKey}>[^/]+?)`; + } + return { + key, + pattern: optional ? `(?:/${interceptionPrefix}${pattern})?` : `/${interceptionPrefix}${pattern}`, + cleanedKey: cleanedKey, + optional, + repeat + }; +} +function getNamedParametrizedRoute(route, prefixRouteKeys, includeSuffix, includePrefix, backreferenceDuplicateKeys, reference = { + names: {}, + intercepted: {} +}) { + const getSafeRouteKey = buildGetSafeRouteKey(); + const routeKeys = {}; + const segments = []; + const inverseParts = []; + // Ensure we don't mutate the original reference object. + reference = structuredClone(reference); + for (const segment of (0, _removetrailingslash.removeTrailingSlash)(route).slice(1).split('/')){ + const hasInterceptionMarker = _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.some((m)=>segment.startsWith(m)); + const paramMatches = segment.match(_getdynamicparam.PARAMETER_PATTERN) // Check for parameters + ; + const interceptionMarker = hasInterceptionMarker ? paramMatches?.[1] : undefined; + let keyPrefix; + if (interceptionMarker && paramMatches?.[2]) { + keyPrefix = prefixRouteKeys ? _constants.NEXT_INTERCEPTION_MARKER_PREFIX : undefined; + reference.intercepted[paramMatches[2]] = interceptionMarker; + } else if (paramMatches?.[2] && reference.intercepted[paramMatches[2]]) { + keyPrefix = prefixRouteKeys ? _constants.NEXT_INTERCEPTION_MARKER_PREFIX : undefined; + } else { + keyPrefix = prefixRouteKeys ? _constants.NEXT_QUERY_PARAM_PREFIX : undefined; + } + if (interceptionMarker && paramMatches && paramMatches[2]) { + // If there's an interception marker, add it to the segments. + const { key, pattern, cleanedKey, repeat, optional } = getSafeKeyFromSegment({ + getSafeRouteKey, + interceptionMarker, + segment: paramMatches[2], + routeKeys, + keyPrefix, + backreferenceDuplicateKeys + }); + segments.push(pattern); + inverseParts.push(`/${paramMatches[1]}:${reference.names[key] ?? cleanedKey}${repeat ? optional ? '*' : '+' : ''}`); + reference.names[key] ??= cleanedKey; + } else if (paramMatches && paramMatches[2]) { + // If there's a prefix, add it to the segments if it's enabled. + if (includePrefix && paramMatches[1]) { + segments.push(`/${(0, _escaperegexp.escapeStringRegexp)(paramMatches[1])}`); + inverseParts.push(`/${paramMatches[1]}`); + } + const { key, pattern, cleanedKey, repeat, optional } = getSafeKeyFromSegment({ + getSafeRouteKey, + segment: paramMatches[2], + routeKeys, + keyPrefix, + backreferenceDuplicateKeys + }); + // Remove the leading slash if includePrefix already added it. + let s = pattern; + if (includePrefix && paramMatches[1]) { + s = s.substring(1); + } + segments.push(s); + inverseParts.push(`/:${reference.names[key] ?? cleanedKey}${repeat ? optional ? '*' : '+' : ''}`); + reference.names[key] ??= cleanedKey; + } else { + segments.push(`/${(0, _escaperegexp.escapeStringRegexp)(segment)}`); + inverseParts.push(`/${segment}`); + } + // If there's a suffix, add it to the segments if it's enabled. + if (includeSuffix && paramMatches && paramMatches[3]) { + segments.push((0, _escaperegexp.escapeStringRegexp)(paramMatches[3])); + inverseParts.push(paramMatches[3]); + } + } + return { + namedParameterizedRoute: segments.join(''), + routeKeys, + pathToRegexpPattern: inverseParts.join(''), + reference + }; +} +function getNamedRouteRegex(normalizedRoute, options) { + const result = getNamedParametrizedRoute(normalizedRoute, options.prefixRouteKeys, options.includeSuffix ?? false, options.includePrefix ?? false, options.backreferenceDuplicateKeys ?? false, options.reference); + let namedRegex = result.namedParameterizedRoute; + if (!options.excludeOptionalTrailingSlash) { + namedRegex += '(?:/)?'; + } + return { + ...getRouteRegex(normalizedRoute, options), + namedRegex: `^${namedRegex}$`, + routeKeys: result.routeKeys, + pathToRegexpPattern: result.pathToRegexpPattern, + reference: result.reference + }; +} +function getNamedMiddlewareRegex(normalizedRoute, options) { + const { parameterizedRoute } = getParametrizedRoute(normalizedRoute, false, false); + const { catchAll = true } = options; + if (parameterizedRoute === '/') { + let catchAllRegex = catchAll ? '.*' : ''; + return { + namedRegex: `^/${catchAllRegex}$` + }; + } + const { namedParameterizedRoute } = getNamedParametrizedRoute(normalizedRoute, false, false, false, false, undefined); + let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : ''; + return { + namedRegex: `^${namedParameterizedRoute}${catchAllGroupedRegex}$` + }; +} + +//# sourceMappingURL=route-regex.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.js.map new file mode 100644 index 0000000000000000000000000000000000000000..509ff9600a86d17e4f8d8ede9aa93169a565e970 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/route-regex.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/route-regex.ts"],"sourcesContent":["import {\n NEXT_INTERCEPTION_MARKER_PREFIX,\n NEXT_QUERY_PARAM_PREFIX,\n} from '../../../../lib/constants'\nimport { INTERCEPTION_ROUTE_MARKERS } from './interception-routes'\nimport { escapeStringRegexp } from '../../escape-regexp'\nimport { removeTrailingSlash } from './remove-trailing-slash'\nimport { PARAMETER_PATTERN, parseMatchedParameter } from './get-dynamic-param'\n\nexport interface Group {\n pos: number\n repeat: boolean\n optional: boolean\n}\n\nexport interface RouteRegex {\n groups: { [groupName: string]: Group }\n re: RegExp\n}\n\nexport type RegexReference = {\n names: Record\n intercepted: Record\n}\n\ntype GetNamedRouteRegexOptions = {\n /**\n * Whether to prefix the route keys with the NEXT_INTERCEPTION_MARKER_PREFIX\n * or NEXT_QUERY_PARAM_PREFIX. This is only relevant when creating the\n * routes-manifest during the build.\n */\n prefixRouteKeys: boolean\n\n /**\n * Whether to include the suffix in the route regex. This means that when you\n * have something like `/[...slug].json` the `.json` part will be included\n * in the regex, yielding `/(.*).json` as the regex.\n */\n includeSuffix?: boolean\n\n /**\n * Whether to include the prefix in the route regex. This means that when you\n * have something like `/[...slug].json` the `/` part will be included\n * in the regex, yielding `^/(.*).json$` as the regex.\n *\n * Note that interception markers will already be included without the need\n */\n includePrefix?: boolean\n\n /**\n * Whether to exclude the optional trailing slash from the route regex.\n */\n excludeOptionalTrailingSlash?: boolean\n\n /**\n * Whether to backtrack duplicate keys. This is only relevant when creating\n * the routes-manifest during the build.\n */\n backreferenceDuplicateKeys?: boolean\n\n /**\n * If provided, this will be used as the reference for the dynamic parameter\n * keys instead of generating them in context. This is currently only used for\n * interception routes.\n */\n reference?: RegexReference\n}\n\ntype GetRouteRegexOptions = {\n /**\n * Whether to include extra parts in the route regex. This means that when you\n * have something like `/[...slug].json` the `.json` part will be included\n * in the regex, yielding `/(.*).json` as the regex.\n */\n includeSuffix?: boolean\n\n /**\n * Whether to include the prefix in the route regex. This means that when you\n * have something like `/[...slug].json` the `/` part will be included\n * in the regex, yielding `^/(.*).json$` as the regex.\n *\n * Note that interception markers will already be included without the need\n * of adding this option.\n */\n includePrefix?: boolean\n\n /**\n * Whether to exclude the optional trailing slash from the route regex.\n */\n excludeOptionalTrailingSlash?: boolean\n}\n\nfunction getParametrizedRoute(\n route: string,\n includeSuffix: boolean,\n includePrefix: boolean\n) {\n const groups: { [groupName: string]: Group } = {}\n let groupIndex = 1\n\n const segments: string[] = []\n for (const segment of removeTrailingSlash(route).slice(1).split('/')) {\n const markerMatch = INTERCEPTION_ROUTE_MARKERS.find((m) =>\n segment.startsWith(m)\n )\n const paramMatches = segment.match(PARAMETER_PATTERN) // Check for parameters\n\n if (markerMatch && paramMatches && paramMatches[2]) {\n const { key, optional, repeat } = parseMatchedParameter(paramMatches[2])\n groups[key] = { pos: groupIndex++, repeat, optional }\n segments.push(`/${escapeStringRegexp(markerMatch)}([^/]+?)`)\n } else if (paramMatches && paramMatches[2]) {\n const { key, repeat, optional } = parseMatchedParameter(paramMatches[2])\n groups[key] = { pos: groupIndex++, repeat, optional }\n\n if (includePrefix && paramMatches[1]) {\n segments.push(`/${escapeStringRegexp(paramMatches[1])}`)\n }\n\n let s = repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)'\n\n // Remove the leading slash if includePrefix already added it.\n if (includePrefix && paramMatches[1]) {\n s = s.substring(1)\n }\n\n segments.push(s)\n } else {\n segments.push(`/${escapeStringRegexp(segment)}`)\n }\n\n // If there's a suffix, add it to the segments if it's enabled.\n if (includeSuffix && paramMatches && paramMatches[3]) {\n segments.push(escapeStringRegexp(paramMatches[3]))\n }\n }\n\n return {\n parameterizedRoute: segments.join(''),\n groups,\n }\n}\n\n/**\n * From a normalized route this function generates a regular expression and\n * a corresponding groups object intended to be used to store matching groups\n * from the regular expression.\n */\nexport function getRouteRegex(\n normalizedRoute: string,\n {\n includeSuffix = false,\n includePrefix = false,\n excludeOptionalTrailingSlash = false,\n }: GetRouteRegexOptions = {}\n): RouteRegex {\n const { parameterizedRoute, groups } = getParametrizedRoute(\n normalizedRoute,\n includeSuffix,\n includePrefix\n )\n\n let re = parameterizedRoute\n if (!excludeOptionalTrailingSlash) {\n re += '(?:/)?'\n }\n\n return {\n re: new RegExp(`^${re}$`),\n groups: groups,\n }\n}\n\n/**\n * Builds a function to generate a minimal routeKey using only a-z and minimal\n * number of characters.\n */\nfunction buildGetSafeRouteKey() {\n let i = 0\n\n return () => {\n let routeKey = ''\n let j = ++i\n while (j > 0) {\n routeKey += String.fromCharCode(97 + ((j - 1) % 26))\n j = Math.floor((j - 1) / 26)\n }\n return routeKey\n }\n}\n\nfunction getSafeKeyFromSegment({\n interceptionMarker,\n getSafeRouteKey,\n segment,\n routeKeys,\n keyPrefix,\n backreferenceDuplicateKeys,\n}: {\n interceptionMarker?: string\n getSafeRouteKey: () => string\n segment: string\n routeKeys: Record\n keyPrefix?: string\n backreferenceDuplicateKeys: boolean\n}) {\n const { key, optional, repeat } = parseMatchedParameter(segment)\n\n // replace any non-word characters since they can break\n // the named regex\n let cleanedKey = key.replace(/\\W/g, '')\n\n if (keyPrefix) {\n cleanedKey = `${keyPrefix}${cleanedKey}`\n }\n let invalidKey = false\n\n // check if the key is still invalid and fallback to using a known\n // safe key\n if (cleanedKey.length === 0 || cleanedKey.length > 30) {\n invalidKey = true\n }\n if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) {\n invalidKey = true\n }\n\n if (invalidKey) {\n cleanedKey = getSafeRouteKey()\n }\n\n const duplicateKey = cleanedKey in routeKeys\n\n if (keyPrefix) {\n routeKeys[cleanedKey] = `${keyPrefix}${key}`\n } else {\n routeKeys[cleanedKey] = key\n }\n\n // if the segment has an interception marker, make sure that's part of the regex pattern\n // this is to ensure that the route with the interception marker doesn't incorrectly match\n // the non-intercepted route (ie /app/(.)[username] should not match /app/[username])\n const interceptionPrefix = interceptionMarker\n ? escapeStringRegexp(interceptionMarker)\n : ''\n\n let pattern: string\n if (duplicateKey && backreferenceDuplicateKeys) {\n // Use a backreference to the key to ensure that the key is the same value\n // in each of the placeholders.\n pattern = `\\\\k<${cleanedKey}>`\n } else if (repeat) {\n pattern = `(?<${cleanedKey}>.+?)`\n } else {\n pattern = `(?<${cleanedKey}>[^/]+?)`\n }\n\n return {\n key,\n pattern: optional\n ? `(?:/${interceptionPrefix}${pattern})?`\n : `/${interceptionPrefix}${pattern}`,\n cleanedKey: cleanedKey,\n optional,\n repeat,\n }\n}\n\nfunction getNamedParametrizedRoute(\n route: string,\n prefixRouteKeys: boolean,\n includeSuffix: boolean,\n includePrefix: boolean,\n backreferenceDuplicateKeys: boolean,\n reference: RegexReference = { names: {}, intercepted: {} }\n) {\n const getSafeRouteKey = buildGetSafeRouteKey()\n const routeKeys: { [named: string]: string } = {}\n\n const segments: string[] = []\n const inverseParts: string[] = []\n\n // Ensure we don't mutate the original reference object.\n reference = structuredClone(reference)\n\n for (const segment of removeTrailingSlash(route).slice(1).split('/')) {\n const hasInterceptionMarker = INTERCEPTION_ROUTE_MARKERS.some((m) =>\n segment.startsWith(m)\n )\n\n const paramMatches = segment.match(PARAMETER_PATTERN) // Check for parameters\n\n const interceptionMarker = hasInterceptionMarker\n ? paramMatches?.[1]\n : undefined\n\n let keyPrefix: string | undefined\n if (interceptionMarker && paramMatches?.[2]) {\n keyPrefix = prefixRouteKeys ? NEXT_INTERCEPTION_MARKER_PREFIX : undefined\n reference.intercepted[paramMatches[2]] = interceptionMarker\n } else if (paramMatches?.[2] && reference.intercepted[paramMatches[2]]) {\n keyPrefix = prefixRouteKeys ? NEXT_INTERCEPTION_MARKER_PREFIX : undefined\n } else {\n keyPrefix = prefixRouteKeys ? NEXT_QUERY_PARAM_PREFIX : undefined\n }\n\n if (interceptionMarker && paramMatches && paramMatches[2]) {\n // If there's an interception marker, add it to the segments.\n const { key, pattern, cleanedKey, repeat, optional } =\n getSafeKeyFromSegment({\n getSafeRouteKey,\n interceptionMarker,\n segment: paramMatches[2],\n routeKeys,\n keyPrefix,\n backreferenceDuplicateKeys,\n })\n\n segments.push(pattern)\n inverseParts.push(\n `/${paramMatches[1]}:${reference.names[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}`\n )\n reference.names[key] ??= cleanedKey\n } else if (paramMatches && paramMatches[2]) {\n // If there's a prefix, add it to the segments if it's enabled.\n if (includePrefix && paramMatches[1]) {\n segments.push(`/${escapeStringRegexp(paramMatches[1])}`)\n inverseParts.push(`/${paramMatches[1]}`)\n }\n\n const { key, pattern, cleanedKey, repeat, optional } =\n getSafeKeyFromSegment({\n getSafeRouteKey,\n segment: paramMatches[2],\n routeKeys,\n keyPrefix,\n backreferenceDuplicateKeys,\n })\n\n // Remove the leading slash if includePrefix already added it.\n let s = pattern\n if (includePrefix && paramMatches[1]) {\n s = s.substring(1)\n }\n\n segments.push(s)\n inverseParts.push(\n `/:${reference.names[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}`\n )\n reference.names[key] ??= cleanedKey\n } else {\n segments.push(`/${escapeStringRegexp(segment)}`)\n inverseParts.push(`/${segment}`)\n }\n\n // If there's a suffix, add it to the segments if it's enabled.\n if (includeSuffix && paramMatches && paramMatches[3]) {\n segments.push(escapeStringRegexp(paramMatches[3]))\n inverseParts.push(paramMatches[3])\n }\n }\n\n return {\n namedParameterizedRoute: segments.join(''),\n routeKeys,\n pathToRegexpPattern: inverseParts.join(''),\n reference,\n }\n}\n\n/**\n * This function extends `getRouteRegex` generating also a named regexp where\n * each group is named along with a routeKeys object that indexes the assigned\n * named group with its corresponding key. When the routeKeys need to be\n * prefixed to uniquely identify internally the \"prefixRouteKey\" arg should\n * be \"true\" currently this is only the case when creating the routes-manifest\n * during the build\n */\nexport function getNamedRouteRegex(\n normalizedRoute: string,\n options: GetNamedRouteRegexOptions\n) {\n const result = getNamedParametrizedRoute(\n normalizedRoute,\n options.prefixRouteKeys,\n options.includeSuffix ?? false,\n options.includePrefix ?? false,\n options.backreferenceDuplicateKeys ?? false,\n options.reference\n )\n\n let namedRegex = result.namedParameterizedRoute\n if (!options.excludeOptionalTrailingSlash) {\n namedRegex += '(?:/)?'\n }\n\n return {\n ...getRouteRegex(normalizedRoute, options),\n namedRegex: `^${namedRegex}$`,\n routeKeys: result.routeKeys,\n pathToRegexpPattern: result.pathToRegexpPattern,\n reference: result.reference,\n }\n}\n\n/**\n * Generates a named regexp.\n * This is intended to be using for build time only.\n */\nexport function getNamedMiddlewareRegex(\n normalizedRoute: string,\n options: {\n catchAll?: boolean\n }\n) {\n const { parameterizedRoute } = getParametrizedRoute(\n normalizedRoute,\n false,\n false\n )\n const { catchAll = true } = options\n if (parameterizedRoute === '/') {\n let catchAllRegex = catchAll ? '.*' : ''\n return {\n namedRegex: `^/${catchAllRegex}$`,\n }\n }\n\n const { namedParameterizedRoute } = getNamedParametrizedRoute(\n normalizedRoute,\n false,\n false,\n false,\n false,\n undefined\n )\n let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : ''\n return {\n namedRegex: `^${namedParameterizedRoute}${catchAllGroupedRegex}$`,\n }\n}\n"],"names":["getNamedMiddlewareRegex","getNamedRouteRegex","getRouteRegex","getParametrizedRoute","route","includeSuffix","includePrefix","groups","groupIndex","segments","segment","removeTrailingSlash","slice","split","markerMatch","INTERCEPTION_ROUTE_MARKERS","find","m","startsWith","paramMatches","match","PARAMETER_PATTERN","key","optional","repeat","parseMatchedParameter","pos","push","escapeStringRegexp","s","substring","parameterizedRoute","join","normalizedRoute","excludeOptionalTrailingSlash","re","RegExp","buildGetSafeRouteKey","i","routeKey","j","String","fromCharCode","Math","floor","getSafeKeyFromSegment","interceptionMarker","getSafeRouteKey","routeKeys","keyPrefix","backreferenceDuplicateKeys","cleanedKey","replace","invalidKey","length","isNaN","parseInt","duplicateKey","interceptionPrefix","pattern","getNamedParametrizedRoute","prefixRouteKeys","reference","names","intercepted","inverseParts","structuredClone","hasInterceptionMarker","some","undefined","NEXT_INTERCEPTION_MARKER_PREFIX","NEXT_QUERY_PARAM_PREFIX","namedParameterizedRoute","pathToRegexpPattern","options","result","namedRegex","catchAll","catchAllRegex","catchAllGroupedRegex"],"mappings":";;;;;;;;;;;;;;;;IAwZgBA,uBAAuB;eAAvBA;;IA/BAC,kBAAkB;eAAlBA;;IArOAC,aAAa;eAAbA;;;2BAjJT;oCACoC;8BACR;qCACC;iCACqB;AAqFzD,SAASC,qBACPC,KAAa,EACbC,aAAsB,EACtBC,aAAsB;IAEtB,MAAMC,SAAyC,CAAC;IAChD,IAAIC,aAAa;IAEjB,MAAMC,WAAqB,EAAE;IAC7B,KAAK,MAAMC,WAAWC,IAAAA,wCAAmB,EAACP,OAAOQ,KAAK,CAAC,GAAGC,KAAK,CAAC,KAAM;QACpE,MAAMC,cAAcC,8CAA0B,CAACC,IAAI,CAAC,CAACC,IACnDP,QAAQQ,UAAU,CAACD;QAErB,MAAME,eAAeT,QAAQU,KAAK,CAACC,kCAAiB,EAAE,uBAAuB;;QAE7E,IAAIP,eAAeK,gBAAgBA,YAAY,CAAC,EAAE,EAAE;YAClD,MAAM,EAAEG,GAAG,EAAEC,QAAQ,EAAEC,MAAM,EAAE,GAAGC,IAAAA,sCAAqB,EAACN,YAAY,CAAC,EAAE;YACvEZ,MAAM,CAACe,IAAI,GAAG;gBAAEI,KAAKlB;gBAAcgB;gBAAQD;YAAS;YACpDd,SAASkB,IAAI,CAAC,CAAC,CAAC,EAAEC,IAAAA,gCAAkB,EAACd,aAAa,QAAQ,CAAC;QAC7D,OAAO,IAAIK,gBAAgBA,YAAY,CAAC,EAAE,EAAE;YAC1C,MAAM,EAAEG,GAAG,EAAEE,MAAM,EAAED,QAAQ,EAAE,GAAGE,IAAAA,sCAAqB,EAACN,YAAY,CAAC,EAAE;YACvEZ,MAAM,CAACe,IAAI,GAAG;gBAAEI,KAAKlB;gBAAcgB;gBAAQD;YAAS;YAEpD,IAAIjB,iBAAiBa,YAAY,CAAC,EAAE,EAAE;gBACpCV,SAASkB,IAAI,CAAC,CAAC,CAAC,EAAEC,IAAAA,gCAAkB,EAACT,YAAY,CAAC,EAAE,GAAG;YACzD;YAEA,IAAIU,IAAIL,SAAUD,WAAW,gBAAgB,WAAY;YAEzD,8DAA8D;YAC9D,IAAIjB,iBAAiBa,YAAY,CAAC,EAAE,EAAE;gBACpCU,IAAIA,EAAEC,SAAS,CAAC;YAClB;YAEArB,SAASkB,IAAI,CAACE;QAChB,OAAO;YACLpB,SAASkB,IAAI,CAAC,CAAC,CAAC,EAAEC,IAAAA,gCAAkB,EAAClB,UAAU;QACjD;QAEA,+DAA+D;QAC/D,IAAIL,iBAAiBc,gBAAgBA,YAAY,CAAC,EAAE,EAAE;YACpDV,SAASkB,IAAI,CAACC,IAAAA,gCAAkB,EAACT,YAAY,CAAC,EAAE;QAClD;IACF;IAEA,OAAO;QACLY,oBAAoBtB,SAASuB,IAAI,CAAC;QAClCzB;IACF;AACF;AAOO,SAASL,cACd+B,eAAuB,EACvB,EACE5B,gBAAgB,KAAK,EACrBC,gBAAgB,KAAK,EACrB4B,+BAA+B,KAAK,EACf,GAAG,CAAC,CAAC;IAE5B,MAAM,EAAEH,kBAAkB,EAAExB,MAAM,EAAE,GAAGJ,qBACrC8B,iBACA5B,eACAC;IAGF,IAAI6B,KAAKJ;IACT,IAAI,CAACG,8BAA8B;QACjCC,MAAM;IACR;IAEA,OAAO;QACLA,IAAI,IAAIC,OAAO,CAAC,CAAC,EAAED,GAAG,CAAC,CAAC;QACxB5B,QAAQA;IACV;AACF;AAEA;;;CAGC,GACD,SAAS8B;IACP,IAAIC,IAAI;IAER,OAAO;QACL,IAAIC,WAAW;QACf,IAAIC,IAAI,EAAEF;QACV,MAAOE,IAAI,EAAG;YACZD,YAAYE,OAAOC,YAAY,CAAC,KAAM,AAACF,CAAAA,IAAI,CAAA,IAAK;YAChDA,IAAIG,KAAKC,KAAK,CAAC,AAACJ,CAAAA,IAAI,CAAA,IAAK;QAC3B;QACA,OAAOD;IACT;AACF;AAEA,SAASM,sBAAsB,EAC7BC,kBAAkB,EAClBC,eAAe,EACfrC,OAAO,EACPsC,SAAS,EACTC,SAAS,EACTC,0BAA0B,EAQ3B;IACC,MAAM,EAAE5B,GAAG,EAAEC,QAAQ,EAAEC,MAAM,EAAE,GAAGC,IAAAA,sCAAqB,EAACf;IAExD,uDAAuD;IACvD,kBAAkB;IAClB,IAAIyC,aAAa7B,IAAI8B,OAAO,CAAC,OAAO;IAEpC,IAAIH,WAAW;QACbE,aAAa,GAAGF,YAAYE,YAAY;IAC1C;IACA,IAAIE,aAAa;IAEjB,kEAAkE;IAClE,WAAW;IACX,IAAIF,WAAWG,MAAM,KAAK,KAAKH,WAAWG,MAAM,GAAG,IAAI;QACrDD,aAAa;IACf;IACA,IAAI,CAACE,MAAMC,SAASL,WAAWvC,KAAK,CAAC,GAAG,MAAM;QAC5CyC,aAAa;IACf;IAEA,IAAIA,YAAY;QACdF,aAAaJ;IACf;IAEA,MAAMU,eAAeN,cAAcH;IAEnC,IAAIC,WAAW;QACbD,SAAS,CAACG,WAAW,GAAG,GAAGF,YAAY3B,KAAK;IAC9C,OAAO;QACL0B,SAAS,CAACG,WAAW,GAAG7B;IAC1B;IAEA,wFAAwF;IACxF,0FAA0F;IAC1F,qFAAqF;IACrF,MAAMoC,qBAAqBZ,qBACvBlB,IAAAA,gCAAkB,EAACkB,sBACnB;IAEJ,IAAIa;IACJ,IAAIF,gBAAgBP,4BAA4B;QAC9C,0EAA0E;QAC1E,+BAA+B;QAC/BS,UAAU,CAAC,IAAI,EAAER,WAAW,CAAC,CAAC;IAChC,OAAO,IAAI3B,QAAQ;QACjBmC,UAAU,CAAC,GAAG,EAAER,WAAW,KAAK,CAAC;IACnC,OAAO;QACLQ,UAAU,CAAC,GAAG,EAAER,WAAW,QAAQ,CAAC;IACtC;IAEA,OAAO;QACL7B;QACAqC,SAASpC,WACL,CAAC,IAAI,EAAEmC,qBAAqBC,QAAQ,EAAE,CAAC,GACvC,CAAC,CAAC,EAAED,qBAAqBC,SAAS;QACtCR,YAAYA;QACZ5B;QACAC;IACF;AACF;AAEA,SAASoC,0BACPxD,KAAa,EACbyD,eAAwB,EACxBxD,aAAsB,EACtBC,aAAsB,EACtB4C,0BAAmC,EACnCY,YAA4B;IAAEC,OAAO,CAAC;IAAGC,aAAa,CAAC;AAAE,CAAC;IAE1D,MAAMjB,kBAAkBV;IACxB,MAAMW,YAAyC,CAAC;IAEhD,MAAMvC,WAAqB,EAAE;IAC7B,MAAMwD,eAAyB,EAAE;IAEjC,wDAAwD;IACxDH,YAAYI,gBAAgBJ;IAE5B,KAAK,MAAMpD,WAAWC,IAAAA,wCAAmB,EAACP,OAAOQ,KAAK,CAAC,GAAGC,KAAK,CAAC,KAAM;QACpE,MAAMsD,wBAAwBpD,8CAA0B,CAACqD,IAAI,CAAC,CAACnD,IAC7DP,QAAQQ,UAAU,CAACD;QAGrB,MAAME,eAAeT,QAAQU,KAAK,CAACC,kCAAiB,EAAE,uBAAuB;;QAE7E,MAAMyB,qBAAqBqB,wBACvBhD,cAAc,CAAC,EAAE,GACjBkD;QAEJ,IAAIpB;QACJ,IAAIH,sBAAsB3B,cAAc,CAAC,EAAE,EAAE;YAC3C8B,YAAYY,kBAAkBS,0CAA+B,GAAGD;YAChEP,UAAUE,WAAW,CAAC7C,YAAY,CAAC,EAAE,CAAC,GAAG2B;QAC3C,OAAO,IAAI3B,cAAc,CAAC,EAAE,IAAI2C,UAAUE,WAAW,CAAC7C,YAAY,CAAC,EAAE,CAAC,EAAE;YACtE8B,YAAYY,kBAAkBS,0CAA+B,GAAGD;QAClE,OAAO;YACLpB,YAAYY,kBAAkBU,kCAAuB,GAAGF;QAC1D;QAEA,IAAIvB,sBAAsB3B,gBAAgBA,YAAY,CAAC,EAAE,EAAE;YACzD,6DAA6D;YAC7D,MAAM,EAAEG,GAAG,EAAEqC,OAAO,EAAER,UAAU,EAAE3B,MAAM,EAAED,QAAQ,EAAE,GAClDsB,sBAAsB;gBACpBE;gBACAD;gBACApC,SAASS,YAAY,CAAC,EAAE;gBACxB6B;gBACAC;gBACAC;YACF;YAEFzC,SAASkB,IAAI,CAACgC;YACdM,aAAatC,IAAI,CACf,CAAC,CAAC,EAAER,YAAY,CAAC,EAAE,CAAC,CAAC,EAAE2C,UAAUC,KAAK,CAACzC,IAAI,IAAI6B,aAAa3B,SAAUD,WAAW,MAAM,MAAO,IAAI;YAEpGuC,UAAUC,KAAK,CAACzC,IAAI,KAAK6B;QAC3B,OAAO,IAAIhC,gBAAgBA,YAAY,CAAC,EAAE,EAAE;YAC1C,+DAA+D;YAC/D,IAAIb,iBAAiBa,YAAY,CAAC,EAAE,EAAE;gBACpCV,SAASkB,IAAI,CAAC,CAAC,CAAC,EAAEC,IAAAA,gCAAkB,EAACT,YAAY,CAAC,EAAE,GAAG;gBACvD8C,aAAatC,IAAI,CAAC,CAAC,CAAC,EAAER,YAAY,CAAC,EAAE,EAAE;YACzC;YAEA,MAAM,EAAEG,GAAG,EAAEqC,OAAO,EAAER,UAAU,EAAE3B,MAAM,EAAED,QAAQ,EAAE,GAClDsB,sBAAsB;gBACpBE;gBACArC,SAASS,YAAY,CAAC,EAAE;gBACxB6B;gBACAC;gBACAC;YACF;YAEF,8DAA8D;YAC9D,IAAIrB,IAAI8B;YACR,IAAIrD,iBAAiBa,YAAY,CAAC,EAAE,EAAE;gBACpCU,IAAIA,EAAEC,SAAS,CAAC;YAClB;YAEArB,SAASkB,IAAI,CAACE;YACdoC,aAAatC,IAAI,CACf,CAAC,EAAE,EAAEmC,UAAUC,KAAK,CAACzC,IAAI,IAAI6B,aAAa3B,SAAUD,WAAW,MAAM,MAAO,IAAI;YAElFuC,UAAUC,KAAK,CAACzC,IAAI,KAAK6B;QAC3B,OAAO;YACL1C,SAASkB,IAAI,CAAC,CAAC,CAAC,EAAEC,IAAAA,gCAAkB,EAAClB,UAAU;YAC/CuD,aAAatC,IAAI,CAAC,CAAC,CAAC,EAAEjB,SAAS;QACjC;QAEA,+DAA+D;QAC/D,IAAIL,iBAAiBc,gBAAgBA,YAAY,CAAC,EAAE,EAAE;YACpDV,SAASkB,IAAI,CAACC,IAAAA,gCAAkB,EAACT,YAAY,CAAC,EAAE;YAChD8C,aAAatC,IAAI,CAACR,YAAY,CAAC,EAAE;QACnC;IACF;IAEA,OAAO;QACLqD,yBAAyB/D,SAASuB,IAAI,CAAC;QACvCgB;QACAyB,qBAAqBR,aAAajC,IAAI,CAAC;QACvC8B;IACF;AACF;AAUO,SAAS7D,mBACdgC,eAAuB,EACvByC,OAAkC;IAElC,MAAMC,SAASf,0BACb3B,iBACAyC,QAAQb,eAAe,EACvBa,QAAQrE,aAAa,IAAI,OACzBqE,QAAQpE,aAAa,IAAI,OACzBoE,QAAQxB,0BAA0B,IAAI,OACtCwB,QAAQZ,SAAS;IAGnB,IAAIc,aAAaD,OAAOH,uBAAuB;IAC/C,IAAI,CAACE,QAAQxC,4BAA4B,EAAE;QACzC0C,cAAc;IAChB;IAEA,OAAO;QACL,GAAG1E,cAAc+B,iBAAiByC,QAAQ;QAC1CE,YAAY,CAAC,CAAC,EAAEA,WAAW,CAAC,CAAC;QAC7B5B,WAAW2B,OAAO3B,SAAS;QAC3ByB,qBAAqBE,OAAOF,mBAAmB;QAC/CX,WAAWa,OAAOb,SAAS;IAC7B;AACF;AAMO,SAAS9D,wBACdiC,eAAuB,EACvByC,OAEC;IAED,MAAM,EAAE3C,kBAAkB,EAAE,GAAG5B,qBAC7B8B,iBACA,OACA;IAEF,MAAM,EAAE4C,WAAW,IAAI,EAAE,GAAGH;IAC5B,IAAI3C,uBAAuB,KAAK;QAC9B,IAAI+C,gBAAgBD,WAAW,OAAO;QACtC,OAAO;YACLD,YAAY,CAAC,EAAE,EAAEE,cAAc,CAAC,CAAC;QACnC;IACF;IAEA,MAAM,EAAEN,uBAAuB,EAAE,GAAGZ,0BAClC3B,iBACA,OACA,OACA,OACA,OACAoC;IAEF,IAAIU,uBAAuBF,WAAW,eAAe;IACrD,OAAO;QACLD,YAAY,CAAC,CAAC,EAAEJ,0BAA0BO,qBAAqB,CAAC,CAAC;IACnE;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2eeef9d73b81cfafbad0b667524b3b344e44ec8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.d.ts @@ -0,0 +1,103 @@ +/** + * A route that can be sorted by specificity. + */ +export type SortableRoute = { + /** + * The source page of the route. This represents the original page that's on + * disk. For example, the `app/[lang]/[...rest]/page.tsx` would have a source + * page of '/[lang]/[...rest]'. + */ + readonly sourcePage: string; + /** + * The page of the route. This represents the final rendered route. For + * example, the `app/[lang]/[...rest]/page.tsx` that was rendered with a lang + * value of `en` would have a page of '/en/[...rest]'. + */ + readonly page: string; +}; +/** + * Determines the specificity of a route segment for sorting purposes. + * + * In Next.js routing, more specific routes should match before less specific ones. + * This function returns a numeric value where lower numbers indicate higher specificity. + * + * Specificity order (most to least specific): + * 1. Static segments (e.g., "about", "api") - return 0 + * 2. Dynamic segments (e.g., "[id]", "[slug]") - return 1 + * 3. Catch-all segments (e.g., "[...slug]") - return 2 + * 4. Optional catch-all segments (e.g., "[[...slug]]") - return 3 + * + * @param segment - A single path segment (e.g., "api", "[id]", "[...slug]") + * @returns A numeric specificity value (0-3, where 0 is most specific) + */ +export declare function getSegmentSpecificity(segment: string): number; +/** + * Compares two route paths using a depth-first traversal approach. + * + * This function implements a deterministic comparison that sorts routes by specificity: + * 1. More specific routes come first (fewer dynamic segments) + * 2. Shorter routes are more specific than longer ones + * 3. Routes with same specificity are sorted lexicographically + * + * The comparison is done segment by segment, left to right, similar to how + * you would traverse a route tree in depth-first order. + * + * @param pathA - First route path to compare (e.g., "/api/users/[id]") + * @param pathB - Second route path to compare (e.g., "/api/[...slug]") + * @returns Negative if pathA is more specific, positive if pathB is more specific, 0 if equal + */ +export declare function compareRouteSegments(pathA: string, pathB: string): number; +/** + * Sorts an array of routes by specificity using a deterministic depth-first traversal approach. + * + * This function implements Next.js route matching priority where more specific routes + * should be matched before less specific ones. The sorting is deterministic and stable, + * meaning identical inputs will always produce identical outputs. + * + * Sorting criteria (in order of priority): + * 1. Source path specificity (primary) + * 2. Page path specificity (secondary) + * 3. Lexicographic ordering (tertiary, for determinism) + * + * Examples of specificity order: + * - "/api/users" (static) comes before "/api/[slug]" (dynamic) + * - "/api/[id]" (dynamic) comes before "/api/[...slug]" (catch-all) + * - "/api/[...slug]" (catch-all) comes before "/api/[[...slug]]" (optional catch-all) + * + * @param routes - Array of routes to sort + * @returns New sorted array (does not mutate input) + */ +export declare function sortSortableRoutes(routes: readonly SortableRoute[]): readonly SortableRoute[]; +/** + * Sorts an array of pages by specificity using a deterministic depth-first + * traversal approach. + * + * @param pages - Array of pages to sort + * @returns New sorted array (does not mutate input) + */ +export declare function sortPages(pages: readonly string[]): readonly string[]; +/** + * Sorts an object by specificity of the keys using a deterministic depth-first traversal approach. + * + * @param obj - object of pages to sort + * @returns New sorted object (does not mutate input) + */ +export declare function sortPagesObject(obj: Readonly>): Record; +/** + * Sorts an array of objects by sourcePage and page using a deterministic + * depth-first traversal approach. + * + * @param objects - Array of objects to sort + * @param getter - Function to get the sourcePage and page from an object + * @returns New sorted array (does not mutate input) + */ +export declare function sortSortableRouteObjects(objects: readonly T[], getter: (object: T) => SortableRoute): readonly T[]; +/** + * Sorts an array of objects by page using a deterministic depth-first traversal + * approach. + * + * @param objects - Array of objects to sort + * @param getter - Function to get the page from an object + * @returns New sorted array (does not mutate input) + */ +export declare function sortPageObjects(objects: readonly T[], getter: (object: T) => string): readonly T[]; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.js new file mode 100644 index 0000000000000000000000000000000000000000..5e4b66e082d3a66848322879ec4cb1f95b18f807 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.js @@ -0,0 +1,183 @@ +/** + * A route that can be sorted by specificity. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + compareRouteSegments: null, + getSegmentSpecificity: null, + sortPageObjects: null, + sortPages: null, + sortPagesObject: null, + sortSortableRouteObjects: null, + sortSortableRoutes: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + compareRouteSegments: function() { + return compareRouteSegments; + }, + getSegmentSpecificity: function() { + return getSegmentSpecificity; + }, + sortPageObjects: function() { + return sortPageObjects; + }, + sortPages: function() { + return sortPages; + }, + sortPagesObject: function() { + return sortPagesObject; + }, + sortSortableRouteObjects: function() { + return sortSortableRouteObjects; + }, + sortSortableRoutes: function() { + return sortSortableRoutes; + } +}); +function getSegmentSpecificity(segment) { + // Static segments are most specific - they match exactly one path + if (!segment.includes('[')) { + return 0; + } + // Optional catch-all [[...param]] is least specific - matches zero or more segments + if (segment.startsWith('[[...') && segment.endsWith(']]')) { + return 3; + } + // Catch-all [...param] is less specific - matches one or more segments + if (segment.startsWith('[...') && segment.endsWith(']')) { + return 2; + } + // Regular dynamic [param] is more specific than catch-all - matches exactly one segment + if (segment.startsWith('[') && segment.endsWith(']')) { + return 1; + } + // Default to static (fallback case) + return 0; +} +function compareRouteSegments(pathA, pathB) { + // Split paths into segments, removing empty strings from leading/trailing slashes + const segmentsA = pathA.split('/').filter(Boolean); + const segmentsB = pathB.split('/').filter(Boolean); + // Compare segment by segment up to the length of the longer path + const maxLength = Math.max(segmentsA.length, segmentsB.length); + for(let i = 0; i < maxLength; i++){ + const segA = segmentsA[i] || ''; + const segB = segmentsB[i] || ''; + // Handle length differences: shorter routes are MORE specific + // Example: "/api" is more specific than "/api/users" + if (!segA && segB) return -1 // pathA is shorter, so more specific + ; + if (segA && !segB) return 1 // pathB is shorter, so more specific + ; + if (!segA && !segB) return 0 // Both paths ended, they're equal + ; + // Compare segment specificity using our specificity scoring + const specificityA = getSegmentSpecificity(segA); + const specificityB = getSegmentSpecificity(segB); + // Lower specificity number = more specific route + // Example: "api" (0) vs "[slug]" (1) - "api" wins + if (specificityA !== specificityB) { + return specificityA - specificityB; + } + // If segments have same specificity, compare lexicographically for determinism + // Example: "[id]" vs "[slug]" - "[id]" comes first alphabetically + if (segA !== segB) { + return segA.localeCompare(segB); + } + // Segments are identical, continue to next segment + } + // All segments compared equally + return 0; +} +/** + * Compares two complete routes for sorting purposes. + * + * Routes are compared with a two-tier priority system: + * 1. Primary: Compare by source path specificity + * 2. Secondary: If sources are equal, compare by page path specificity + * + * This ensures that routes are primarily organized by their source patterns, + * with page-specific variations grouped together. + * + * @param a - First route to compare + * @param b - Second route to compare + * @returns Negative if route a should come first, positive if route b should come first, 0 if equal + */ function compareSortableRoutes(a, b) { + // First compare by source specificity - this is the primary sorting criterion + // Source represents the original route pattern and takes precedence + const sourceResult = compareRouteSegments(a.sourcePage, b.sourcePage); + if (sourceResult !== 0) return sourceResult; + // If sources are identical, compare by page specificity as a tiebreaker + // Page represents the final rendered route and provides secondary ordering + return compareRouteSegments(a.page, b.page); +} +function sortSortableRoutes(routes) { + // Because sort is always in-place, we need to create a shallow copy to avoid + // mutating the input array. + return [ + ...routes + ].sort(compareSortableRoutes); +} +function sortPages(pages) { + // Because sort is always in-place, we need to create a shallow copy to avoid + // mutating the input array. + return [ + ...pages + ].sort(compareRouteSegments); +} +function sortPagesObject(obj) { + // Because sort is always in-place, we need to create a shallow copy to avoid + // mutating the input. + return Object.keys(obj).sort(compareRouteSegments).reduce((acc, key)=>{ + acc[key] = obj[key]; + return acc; + }, {}); +} +function sortSortableRouteObjects(objects, getter) { + // Create a SortableRoute for each object. + const routes = []; + for (const object of objects){ + const route = getter(object); + routes.push({ + ...route, + object + }); + } + // In-place sort the SortableRoutes. + routes.sort(compareSortableRoutes); + // Map the sorted SortableRoutes back to the original objects. + return routes.map(({ object })=>object); +} +function sortPageObjects(objects, getter) { + const indexes = {}; + const pages = new Set(); + for(let i = 0; i < objects.length; i++){ + const object = objects[i]; + const page = getter(object); + indexes[page]?.push(i) || (indexes[page] = [ + i + ]); + pages.add(page); + } + // Sort the unique pages. + const sortedPages = Array.from(pages).sort(compareRouteSegments); + // Map the sorted pages back to the original objects. + return sortedPages.reduce((sortedObjects, page)=>{ + // Add all objects for this page to the sorted array. + for (const i of indexes[page]){ + sortedObjects.push(objects[i]); + } + // Return the sorted array. + return sortedObjects; + }, []); +} + +//# sourceMappingURL=sortable-routes.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b275ef2eb8904572a6443c37508ee4c0a5797447 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sortable-routes.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/sortable-routes.ts"],"sourcesContent":["/**\n * A route that can be sorted by specificity.\n */\nexport type SortableRoute = {\n /**\n * The source page of the route. This represents the original page that's on\n * disk. For example, the `app/[lang]/[...rest]/page.tsx` would have a source\n * page of '/[lang]/[...rest]'.\n */\n readonly sourcePage: string\n\n /**\n * The page of the route. This represents the final rendered route. For\n * example, the `app/[lang]/[...rest]/page.tsx` that was rendered with a lang\n * value of `en` would have a page of '/en/[...rest]'.\n */\n readonly page: string\n}\n\n/**\n * Determines the specificity of a route segment for sorting purposes.\n *\n * In Next.js routing, more specific routes should match before less specific ones.\n * This function returns a numeric value where lower numbers indicate higher specificity.\n *\n * Specificity order (most to least specific):\n * 1. Static segments (e.g., \"about\", \"api\") - return 0\n * 2. Dynamic segments (e.g., \"[id]\", \"[slug]\") - return 1\n * 3. Catch-all segments (e.g., \"[...slug]\") - return 2\n * 4. Optional catch-all segments (e.g., \"[[...slug]]\") - return 3\n *\n * @param segment - A single path segment (e.g., \"api\", \"[id]\", \"[...slug]\")\n * @returns A numeric specificity value (0-3, where 0 is most specific)\n */\nexport function getSegmentSpecificity(segment: string): number {\n // Static segments are most specific - they match exactly one path\n if (!segment.includes('[')) {\n return 0\n }\n\n // Optional catch-all [[...param]] is least specific - matches zero or more segments\n if (segment.startsWith('[[...') && segment.endsWith(']]')) {\n return 3\n }\n\n // Catch-all [...param] is less specific - matches one or more segments\n if (segment.startsWith('[...') && segment.endsWith(']')) {\n return 2\n }\n\n // Regular dynamic [param] is more specific than catch-all - matches exactly one segment\n if (segment.startsWith('[') && segment.endsWith(']')) {\n return 1\n }\n\n // Default to static (fallback case)\n return 0\n}\n\n/**\n * Compares two route paths using a depth-first traversal approach.\n *\n * This function implements a deterministic comparison that sorts routes by specificity:\n * 1. More specific routes come first (fewer dynamic segments)\n * 2. Shorter routes are more specific than longer ones\n * 3. Routes with same specificity are sorted lexicographically\n *\n * The comparison is done segment by segment, left to right, similar to how\n * you would traverse a route tree in depth-first order.\n *\n * @param pathA - First route path to compare (e.g., \"/api/users/[id]\")\n * @param pathB - Second route path to compare (e.g., \"/api/[...slug]\")\n * @returns Negative if pathA is more specific, positive if pathB is more specific, 0 if equal\n */\nexport function compareRouteSegments(pathA: string, pathB: string): number {\n // Split paths into segments, removing empty strings from leading/trailing slashes\n const segmentsA = pathA.split('/').filter(Boolean)\n const segmentsB = pathB.split('/').filter(Boolean)\n\n // Compare segment by segment up to the length of the longer path\n const maxLength = Math.max(segmentsA.length, segmentsB.length)\n\n for (let i = 0; i < maxLength; i++) {\n const segA = segmentsA[i] || ''\n const segB = segmentsB[i] || ''\n\n // Handle length differences: shorter routes are MORE specific\n // Example: \"/api\" is more specific than \"/api/users\"\n if (!segA && segB) return -1 // pathA is shorter, so more specific\n if (segA && !segB) return 1 // pathB is shorter, so more specific\n if (!segA && !segB) return 0 // Both paths ended, they're equal\n\n // Compare segment specificity using our specificity scoring\n const specificityA = getSegmentSpecificity(segA)\n const specificityB = getSegmentSpecificity(segB)\n\n // Lower specificity number = more specific route\n // Example: \"api\" (0) vs \"[slug]\" (1) - \"api\" wins\n if (specificityA !== specificityB) {\n return specificityA - specificityB\n }\n\n // If segments have same specificity, compare lexicographically for determinism\n // Example: \"[id]\" vs \"[slug]\" - \"[id]\" comes first alphabetically\n if (segA !== segB) {\n return segA.localeCompare(segB)\n }\n\n // Segments are identical, continue to next segment\n }\n\n // All segments compared equally\n return 0\n}\n\n/**\n * Compares two complete routes for sorting purposes.\n *\n * Routes are compared with a two-tier priority system:\n * 1. Primary: Compare by source path specificity\n * 2. Secondary: If sources are equal, compare by page path specificity\n *\n * This ensures that routes are primarily organized by their source patterns,\n * with page-specific variations grouped together.\n *\n * @param a - First route to compare\n * @param b - Second route to compare\n * @returns Negative if route a should come first, positive if route b should come first, 0 if equal\n */\nfunction compareSortableRoutes(a: SortableRoute, b: SortableRoute): number {\n // First compare by source specificity - this is the primary sorting criterion\n // Source represents the original route pattern and takes precedence\n const sourceResult = compareRouteSegments(a.sourcePage, b.sourcePage)\n if (sourceResult !== 0) return sourceResult\n\n // If sources are identical, compare by page specificity as a tiebreaker\n // Page represents the final rendered route and provides secondary ordering\n return compareRouteSegments(a.page, b.page)\n}\n\n/**\n * Sorts an array of routes by specificity using a deterministic depth-first traversal approach.\n *\n * This function implements Next.js route matching priority where more specific routes\n * should be matched before less specific ones. The sorting is deterministic and stable,\n * meaning identical inputs will always produce identical outputs.\n *\n * Sorting criteria (in order of priority):\n * 1. Source path specificity (primary)\n * 2. Page path specificity (secondary)\n * 3. Lexicographic ordering (tertiary, for determinism)\n *\n * Examples of specificity order:\n * - \"/api/users\" (static) comes before \"/api/[slug]\" (dynamic)\n * - \"/api/[id]\" (dynamic) comes before \"/api/[...slug]\" (catch-all)\n * - \"/api/[...slug]\" (catch-all) comes before \"/api/[[...slug]]\" (optional catch-all)\n *\n * @param routes - Array of routes to sort\n * @returns New sorted array (does not mutate input)\n */\nexport function sortSortableRoutes(\n routes: readonly SortableRoute[]\n): readonly SortableRoute[] {\n // Because sort is always in-place, we need to create a shallow copy to avoid\n // mutating the input array.\n return [...routes].sort(compareSortableRoutes)\n}\n\n/**\n * Sorts an array of pages by specificity using a deterministic depth-first\n * traversal approach.\n *\n * @param pages - Array of pages to sort\n * @returns New sorted array (does not mutate input)\n */\nexport function sortPages(pages: readonly string[]): readonly string[] {\n // Because sort is always in-place, we need to create a shallow copy to avoid\n // mutating the input array.\n return [...pages].sort(compareRouteSegments)\n}\n\n/**\n * Sorts an object by specificity of the keys using a deterministic depth-first traversal approach.\n *\n * @param obj - object of pages to sort\n * @returns New sorted object (does not mutate input)\n */\nexport function sortPagesObject(\n obj: Readonly>\n): Record {\n // Because sort is always in-place, we need to create a shallow copy to avoid\n // mutating the input.\n return Object.keys(obj)\n .sort(compareRouteSegments)\n .reduce(\n (acc, key) => {\n acc[key] = obj[key]\n return acc\n },\n {} as Record\n )\n}\n\n/**\n * Sorts an array of objects by sourcePage and page using a deterministic\n * depth-first traversal approach.\n *\n * @param objects - Array of objects to sort\n * @param getter - Function to get the sourcePage and page from an object\n * @returns New sorted array (does not mutate input)\n */\nexport function sortSortableRouteObjects(\n objects: readonly T[],\n getter: (object: T) => SortableRoute\n): readonly T[] {\n // Create a SortableRoute for each object.\n const routes: Array = []\n for (const object of objects) {\n const route = getter(object)\n routes.push({ ...route, object })\n }\n\n // In-place sort the SortableRoutes.\n routes.sort(compareSortableRoutes)\n\n // Map the sorted SortableRoutes back to the original objects.\n return routes.map(({ object }) => object)\n}\n\n/**\n * Sorts an array of objects by page using a deterministic depth-first traversal\n * approach.\n *\n * @param objects - Array of objects to sort\n * @param getter - Function to get the page from an object\n * @returns New sorted array (does not mutate input)\n */\nexport function sortPageObjects(\n objects: readonly T[],\n getter: (object: T) => string\n): readonly T[] {\n const indexes: Record = {}\n const pages: Set = new Set()\n for (let i = 0; i < objects.length; i++) {\n const object = objects[i]\n const page = getter(object)\n indexes[page]?.push(i) || (indexes[page] = [i])\n pages.add(page)\n }\n\n // Sort the unique pages.\n const sortedPages = Array.from(pages).sort(compareRouteSegments)\n\n // Map the sorted pages back to the original objects.\n return sortedPages.reduce((sortedObjects, page) => {\n // Add all objects for this page to the sorted array.\n for (const i of indexes[page]) {\n sortedObjects.push(objects[i])\n }\n\n // Return the sorted array.\n return sortedObjects\n }, [])\n}\n"],"names":["compareRouteSegments","getSegmentSpecificity","sortPageObjects","sortPages","sortPagesObject","sortSortableRouteObjects","sortSortableRoutes","segment","includes","startsWith","endsWith","pathA","pathB","segmentsA","split","filter","Boolean","segmentsB","maxLength","Math","max","length","i","segA","segB","specificityA","specificityB","localeCompare","compareSortableRoutes","a","b","sourceResult","sourcePage","page","routes","sort","pages","obj","Object","keys","reduce","acc","key","objects","getter","object","route","push","map","indexes","Set","add","sortedPages","Array","from","sortedObjects"],"mappings":"AAAA;;CAEC;;;;;;;;;;;;;;;;;;;;IAwEeA,oBAAoB;eAApBA;;IAxCAC,qBAAqB;eAArBA;;IA2MAC,eAAe;eAAfA;;IA9DAC,SAAS;eAATA;;IAYAC,eAAe;eAAfA;;IAwBAC,wBAAwB;eAAxBA;;IAnDAC,kBAAkB;eAAlBA;;;AA9HT,SAASL,sBAAsBM,OAAe;IACnD,kEAAkE;IAClE,IAAI,CAACA,QAAQC,QAAQ,CAAC,MAAM;QAC1B,OAAO;IACT;IAEA,oFAAoF;IACpF,IAAID,QAAQE,UAAU,CAAC,YAAYF,QAAQG,QAAQ,CAAC,OAAO;QACzD,OAAO;IACT;IAEA,uEAAuE;IACvE,IAAIH,QAAQE,UAAU,CAAC,WAAWF,QAAQG,QAAQ,CAAC,MAAM;QACvD,OAAO;IACT;IAEA,wFAAwF;IACxF,IAAIH,QAAQE,UAAU,CAAC,QAAQF,QAAQG,QAAQ,CAAC,MAAM;QACpD,OAAO;IACT;IAEA,oCAAoC;IACpC,OAAO;AACT;AAiBO,SAASV,qBAAqBW,KAAa,EAAEC,KAAa;IAC/D,kFAAkF;IAClF,MAAMC,YAAYF,MAAMG,KAAK,CAAC,KAAKC,MAAM,CAACC;IAC1C,MAAMC,YAAYL,MAAME,KAAK,CAAC,KAAKC,MAAM,CAACC;IAE1C,iEAAiE;IACjE,MAAME,YAAYC,KAAKC,GAAG,CAACP,UAAUQ,MAAM,EAAEJ,UAAUI,MAAM;IAE7D,IAAK,IAAIC,IAAI,GAAGA,IAAIJ,WAAWI,IAAK;QAClC,MAAMC,OAAOV,SAAS,CAACS,EAAE,IAAI;QAC7B,MAAME,OAAOP,SAAS,CAACK,EAAE,IAAI;QAE7B,8DAA8D;QAC9D,qDAAqD;QACrD,IAAI,CAACC,QAAQC,MAAM,OAAO,CAAC,EAAE,qCAAqC;;QAClE,IAAID,QAAQ,CAACC,MAAM,OAAO,EAAE,qCAAqC;;QACjE,IAAI,CAACD,QAAQ,CAACC,MAAM,OAAO,EAAE,kCAAkC;;QAE/D,4DAA4D;QAC5D,MAAMC,eAAexB,sBAAsBsB;QAC3C,MAAMG,eAAezB,sBAAsBuB;QAE3C,iDAAiD;QACjD,kDAAkD;QAClD,IAAIC,iBAAiBC,cAAc;YACjC,OAAOD,eAAeC;QACxB;QAEA,+EAA+E;QAC/E,kEAAkE;QAClE,IAAIH,SAASC,MAAM;YACjB,OAAOD,KAAKI,aAAa,CAACH;QAC5B;IAEA,mDAAmD;IACrD;IAEA,gCAAgC;IAChC,OAAO;AACT;AAEA;;;;;;;;;;;;;CAaC,GACD,SAASI,sBAAsBC,CAAgB,EAAEC,CAAgB;IAC/D,8EAA8E;IAC9E,oEAAoE;IACpE,MAAMC,eAAe/B,qBAAqB6B,EAAEG,UAAU,EAAEF,EAAEE,UAAU;IACpE,IAAID,iBAAiB,GAAG,OAAOA;IAE/B,wEAAwE;IACxE,2EAA2E;IAC3E,OAAO/B,qBAAqB6B,EAAEI,IAAI,EAAEH,EAAEG,IAAI;AAC5C;AAsBO,SAAS3B,mBACd4B,MAAgC;IAEhC,6EAA6E;IAC7E,4BAA4B;IAC5B,OAAO;WAAIA;KAAO,CAACC,IAAI,CAACP;AAC1B;AASO,SAASzB,UAAUiC,KAAwB;IAChD,6EAA6E;IAC7E,4BAA4B;IAC5B,OAAO;WAAIA;KAAM,CAACD,IAAI,CAACnC;AACzB;AAQO,SAASI,gBACdiC,GAAgC;IAEhC,6EAA6E;IAC7E,sBAAsB;IACtB,OAAOC,OAAOC,IAAI,CAACF,KAChBF,IAAI,CAACnC,sBACLwC,MAAM,CACL,CAACC,KAAKC;QACJD,GAAG,CAACC,IAAI,GAAGL,GAAG,CAACK,IAAI;QACnB,OAAOD;IACT,GACA,CAAC;AAEP;AAUO,SAASpC,yBACdsC,OAAqB,EACrBC,MAAoC;IAEpC,0CAA0C;IAC1C,MAAMV,SAA+C,EAAE;IACvD,KAAK,MAAMW,UAAUF,QAAS;QAC5B,MAAMG,QAAQF,OAAOC;QACrBX,OAAOa,IAAI,CAAC;YAAE,GAAGD,KAAK;YAAED;QAAO;IACjC;IAEA,oCAAoC;IACpCX,OAAOC,IAAI,CAACP;IAEZ,8DAA8D;IAC9D,OAAOM,OAAOc,GAAG,CAAC,CAAC,EAAEH,MAAM,EAAE,GAAKA;AACpC;AAUO,SAAS3C,gBACdyC,OAAqB,EACrBC,MAA6B;IAE7B,MAAMK,UAAoC,CAAC;IAC3C,MAAMb,QAAqB,IAAIc;IAC/B,IAAK,IAAI5B,IAAI,GAAGA,IAAIqB,QAAQtB,MAAM,EAAEC,IAAK;QACvC,MAAMuB,SAASF,OAAO,CAACrB,EAAE;QACzB,MAAMW,OAAOW,OAAOC;QACpBI,OAAO,CAAChB,KAAK,EAAEc,KAAKzB,MAAO2B,CAAAA,OAAO,CAAChB,KAAK,GAAG;YAACX;SAAE,AAAD;QAC7Cc,MAAMe,GAAG,CAAClB;IACZ;IAEA,yBAAyB;IACzB,MAAMmB,cAAcC,MAAMC,IAAI,CAAClB,OAAOD,IAAI,CAACnC;IAE3C,qDAAqD;IACrD,OAAOoD,YAAYZ,MAAM,CAAM,CAACe,eAAetB;QAC7C,qDAAqD;QACrD,KAAK,MAAMX,KAAK2B,OAAO,CAAChB,KAAK,CAAE;YAC7BsB,cAAcR,IAAI,CAACJ,OAAO,CAACrB,EAAE;QAC/B;QAEA,2BAA2B;QAC3B,OAAOiC;IACT,GAAG,EAAE;AACP","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fdc23e26ddb5bad2c80eb28dd1d382cc6309400 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated Use `sortSortableRoutes` or `sortPages` instead. + */ +export declare function getSortedRoutes(normalizedPages: ReadonlyArray): string[]; +/** + * @deprecated Use `sortSortableRouteObjects` or `sortPageObjects` instead. + */ +export declare function getSortedRouteObjects(objects: T[], getter: (obj: T) => string): T[]; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js new file mode 100644 index 0000000000000000000000000000000000000000..5b54d42acb7b9c7f0bd70d3c48c1d4002fb4f67c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js @@ -0,0 +1,200 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getSortedRouteObjects: null, + getSortedRoutes: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getSortedRouteObjects: function() { + return getSortedRouteObjects; + }, + getSortedRoutes: function() { + return getSortedRoutes; + } +}); +class UrlNode { + insert(urlPath) { + this._insert(urlPath.split('/').filter(Boolean), [], false); + } + smoosh() { + return this._smoosh(); + } + _smoosh(prefix = '/') { + const childrenPaths = [ + ...this.children.keys() + ].sort(); + if (this.slugName !== null) { + childrenPaths.splice(childrenPaths.indexOf('[]'), 1); + } + if (this.restSlugName !== null) { + childrenPaths.splice(childrenPaths.indexOf('[...]'), 1); + } + if (this.optionalRestSlugName !== null) { + childrenPaths.splice(childrenPaths.indexOf('[[...]]'), 1); + } + const routes = childrenPaths.map((c)=>this.children.get(c)._smoosh(`${prefix}${c}/`)).reduce((prev, curr)=>[ + ...prev, + ...curr + ], []); + if (this.slugName !== null) { + routes.push(...this.children.get('[]')._smoosh(`${prefix}[${this.slugName}]/`)); + } + if (!this.placeholder) { + const r = prefix === '/' ? '/' : prefix.slice(0, -1); + if (this.optionalRestSlugName != null) { + throw new Error(`You cannot define a route with the same specificity as a optional catch-all route ("${r}" and "${r}[[...${this.optionalRestSlugName}]]").`); + } + routes.unshift(r); + } + if (this.restSlugName !== null) { + routes.push(...this.children.get('[...]')._smoosh(`${prefix}[...${this.restSlugName}]/`)); + } + if (this.optionalRestSlugName !== null) { + routes.push(...this.children.get('[[...]]')._smoosh(`${prefix}[[...${this.optionalRestSlugName}]]/`)); + } + return routes; + } + _insert(urlPaths, slugNames, isCatchAll) { + if (urlPaths.length === 0) { + this.placeholder = false; + return; + } + if (isCatchAll) { + throw new Error(`Catch-all must be the last part of the URL.`); + } + // The next segment in the urlPaths list + let nextSegment = urlPaths[0]; + // Check if the segment matches `[something]` + if (nextSegment.startsWith('[') && nextSegment.endsWith(']')) { + // Strip `[` and `]`, leaving only `something` + let segmentName = nextSegment.slice(1, -1); + let isOptional = false; + if (segmentName.startsWith('[') && segmentName.endsWith(']')) { + // Strip optional `[` and `]`, leaving only `something` + segmentName = segmentName.slice(1, -1); + isOptional = true; + } + if (segmentName.startsWith('…')) { + throw new Error(`Detected a three-dot character ('…') at ('${segmentName}'). Did you mean ('...')?`); + } + if (segmentName.startsWith('...')) { + // Strip `...`, leaving only `something` + segmentName = segmentName.substring(3); + isCatchAll = true; + } + if (segmentName.startsWith('[') || segmentName.endsWith(']')) { + throw new Error(`Segment names may not start or end with extra brackets ('${segmentName}').`); + } + if (segmentName.startsWith('.')) { + throw new Error(`Segment names may not start with erroneous periods ('${segmentName}').`); + } + function handleSlug(previousSlug, nextSlug) { + if (previousSlug !== null) { + // If the specific segment already has a slug but the slug is not `something` + // This prevents collisions like: + // pages/[post]/index.js + // pages/[id]/index.js + // Because currently multiple dynamic params on the same segment level are not supported + if (previousSlug !== nextSlug) { + // TODO: This error seems to be confusing for users, needs an error link, the description can be based on above comment. + throw new Error(`You cannot use different slug names for the same dynamic path ('${previousSlug}' !== '${nextSlug}').`); + } + } + slugNames.forEach((slug)=>{ + if (slug === nextSlug) { + throw new Error(`You cannot have the same slug name "${nextSlug}" repeat within a single dynamic path`); + } + if (slug.replace(/\W/g, '') === nextSegment.replace(/\W/g, '')) { + throw new Error(`You cannot have the slug names "${slug}" and "${nextSlug}" differ only by non-word symbols within a single dynamic path`); + } + }); + slugNames.push(nextSlug); + } + if (isCatchAll) { + if (isOptional) { + if (this.restSlugName != null) { + throw new Error(`You cannot use both an required and optional catch-all route at the same level ("[...${this.restSlugName}]" and "${urlPaths[0]}" ).`); + } + handleSlug(this.optionalRestSlugName, segmentName); + // slugName is kept as it can only be one particular slugName + this.optionalRestSlugName = segmentName; + // nextSegment is overwritten to [[...]] so that it can later be sorted specifically + nextSegment = '[[...]]'; + } else { + if (this.optionalRestSlugName != null) { + throw new Error(`You cannot use both an optional and required catch-all route at the same level ("[[...${this.optionalRestSlugName}]]" and "${urlPaths[0]}").`); + } + handleSlug(this.restSlugName, segmentName); + // slugName is kept as it can only be one particular slugName + this.restSlugName = segmentName; + // nextSegment is overwritten to [...] so that it can later be sorted specifically + nextSegment = '[...]'; + } + } else { + if (isOptional) { + throw new Error(`Optional route parameters are not yet supported ("${urlPaths[0]}").`); + } + handleSlug(this.slugName, segmentName); + // slugName is kept as it can only be one particular slugName + this.slugName = segmentName; + // nextSegment is overwritten to [] so that it can later be sorted specifically + nextSegment = '[]'; + } + } + // If this UrlNode doesn't have the nextSegment yet we create a new child UrlNode + if (!this.children.has(nextSegment)) { + this.children.set(nextSegment, new UrlNode()); + } + this.children.get(nextSegment)._insert(urlPaths.slice(1), slugNames, isCatchAll); + } + constructor(){ + this.placeholder = true; + this.children = new Map(); + this.slugName = null; + this.restSlugName = null; + this.optionalRestSlugName = null; + } +} +function getSortedRoutes(normalizedPages) { + // First the UrlNode is created, and every UrlNode can have only 1 dynamic segment + // Eg you can't have pages/[post]/abc.js and pages/[hello]/something-else.js + // Only 1 dynamic segment per nesting level + // So in the case that is test/e2e/dynamic-routing it'll be this: + // pages/[post]/comments.js + // pages/blog/[post]/comment/[id].js + // Both are fine because `pages/[post]` and `pages/blog` are on the same level + // So in this case `UrlNode` created here has `this.slugName === 'post'` + // And since your PR passed through `slugName` as an array basically it'd including it in too many possibilities + // Instead what has to be passed through is the upwards path's dynamic names + const root = new UrlNode(); + // Here the `root` gets injected multiple paths, and insert will break them up into sublevels + normalizedPages.forEach((pagePath)=>root.insert(pagePath)); + // Smoosh will then sort those sublevels up to the point where you get the correct route definition priority + return root.smoosh(); +} +function getSortedRouteObjects(objects, getter) { + // We're assuming here that all the pathnames are unique, that way we can + // sort the list and use the index as the key. + const indexes = {}; + const pathnames = []; + for(let i = 0; i < objects.length; i++){ + const pathname = getter(objects[i]); + indexes[pathname] = i; + pathnames[i] = pathname; + } + // Sort the pathnames. + const sorted = getSortedRoutes(pathnames); + // Map the sorted pathnames back to the original objects using the new sorted + // index. + return sorted.map((pathname)=>objects[indexes[pathname]]); +} + +//# sourceMappingURL=sorted-routes.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ccb026738834d6fc79b168823193ae2cb8b628bb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/sorted-routes.ts"],"sourcesContent":["class UrlNode {\n placeholder: boolean = true\n children: Map = new Map()\n slugName: string | null = null\n restSlugName: string | null = null\n optionalRestSlugName: string | null = null\n\n insert(urlPath: string): void {\n this._insert(urlPath.split('/').filter(Boolean), [], false)\n }\n\n smoosh(): string[] {\n return this._smoosh()\n }\n\n private _smoosh(prefix: string = '/'): string[] {\n const childrenPaths = [...this.children.keys()].sort()\n if (this.slugName !== null) {\n childrenPaths.splice(childrenPaths.indexOf('[]'), 1)\n }\n if (this.restSlugName !== null) {\n childrenPaths.splice(childrenPaths.indexOf('[...]'), 1)\n }\n if (this.optionalRestSlugName !== null) {\n childrenPaths.splice(childrenPaths.indexOf('[[...]]'), 1)\n }\n\n const routes = childrenPaths\n .map((c) => this.children.get(c)!._smoosh(`${prefix}${c}/`))\n .reduce((prev, curr) => [...prev, ...curr], [])\n\n if (this.slugName !== null) {\n routes.push(\n ...this.children.get('[]')!._smoosh(`${prefix}[${this.slugName}]/`)\n )\n }\n\n if (!this.placeholder) {\n const r = prefix === '/' ? '/' : prefix.slice(0, -1)\n if (this.optionalRestSlugName != null) {\n throw new Error(\n `You cannot define a route with the same specificity as a optional catch-all route (\"${r}\" and \"${r}[[...${this.optionalRestSlugName}]]\").`\n )\n }\n\n routes.unshift(r)\n }\n\n if (this.restSlugName !== null) {\n routes.push(\n ...this.children\n .get('[...]')!\n ._smoosh(`${prefix}[...${this.restSlugName}]/`)\n )\n }\n\n if (this.optionalRestSlugName !== null) {\n routes.push(\n ...this.children\n .get('[[...]]')!\n ._smoosh(`${prefix}[[...${this.optionalRestSlugName}]]/`)\n )\n }\n\n return routes\n }\n\n private _insert(\n urlPaths: string[],\n slugNames: string[],\n isCatchAll: boolean\n ): void {\n if (urlPaths.length === 0) {\n this.placeholder = false\n return\n }\n\n if (isCatchAll) {\n throw new Error(`Catch-all must be the last part of the URL.`)\n }\n\n // The next segment in the urlPaths list\n let nextSegment = urlPaths[0]\n\n // Check if the segment matches `[something]`\n if (nextSegment.startsWith('[') && nextSegment.endsWith(']')) {\n // Strip `[` and `]`, leaving only `something`\n let segmentName = nextSegment.slice(1, -1)\n\n let isOptional = false\n if (segmentName.startsWith('[') && segmentName.endsWith(']')) {\n // Strip optional `[` and `]`, leaving only `something`\n segmentName = segmentName.slice(1, -1)\n isOptional = true\n }\n\n if (segmentName.startsWith('…')) {\n throw new Error(\n `Detected a three-dot character ('…') at ('${segmentName}'). Did you mean ('...')?`\n )\n }\n\n if (segmentName.startsWith('...')) {\n // Strip `...`, leaving only `something`\n segmentName = segmentName.substring(3)\n isCatchAll = true\n }\n\n if (segmentName.startsWith('[') || segmentName.endsWith(']')) {\n throw new Error(\n `Segment names may not start or end with extra brackets ('${segmentName}').`\n )\n }\n\n if (segmentName.startsWith('.')) {\n throw new Error(\n `Segment names may not start with erroneous periods ('${segmentName}').`\n )\n }\n\n function handleSlug(previousSlug: string | null, nextSlug: string) {\n if (previousSlug !== null) {\n // If the specific segment already has a slug but the slug is not `something`\n // This prevents collisions like:\n // pages/[post]/index.js\n // pages/[id]/index.js\n // Because currently multiple dynamic params on the same segment level are not supported\n if (previousSlug !== nextSlug) {\n // TODO: This error seems to be confusing for users, needs an error link, the description can be based on above comment.\n throw new Error(\n `You cannot use different slug names for the same dynamic path ('${previousSlug}' !== '${nextSlug}').`\n )\n }\n }\n\n slugNames.forEach((slug) => {\n if (slug === nextSlug) {\n throw new Error(\n `You cannot have the same slug name \"${nextSlug}\" repeat within a single dynamic path`\n )\n }\n\n if (slug.replace(/\\W/g, '') === nextSegment.replace(/\\W/g, '')) {\n throw new Error(\n `You cannot have the slug names \"${slug}\" and \"${nextSlug}\" differ only by non-word symbols within a single dynamic path`\n )\n }\n })\n\n slugNames.push(nextSlug)\n }\n\n if (isCatchAll) {\n if (isOptional) {\n if (this.restSlugName != null) {\n throw new Error(\n `You cannot use both an required and optional catch-all route at the same level (\"[...${this.restSlugName}]\" and \"${urlPaths[0]}\" ).`\n )\n }\n\n handleSlug(this.optionalRestSlugName, segmentName)\n // slugName is kept as it can only be one particular slugName\n this.optionalRestSlugName = segmentName\n // nextSegment is overwritten to [[...]] so that it can later be sorted specifically\n nextSegment = '[[...]]'\n } else {\n if (this.optionalRestSlugName != null) {\n throw new Error(\n `You cannot use both an optional and required catch-all route at the same level (\"[[...${this.optionalRestSlugName}]]\" and \"${urlPaths[0]}\").`\n )\n }\n\n handleSlug(this.restSlugName, segmentName)\n // slugName is kept as it can only be one particular slugName\n this.restSlugName = segmentName\n // nextSegment is overwritten to [...] so that it can later be sorted specifically\n nextSegment = '[...]'\n }\n } else {\n if (isOptional) {\n throw new Error(\n `Optional route parameters are not yet supported (\"${urlPaths[0]}\").`\n )\n }\n handleSlug(this.slugName, segmentName)\n // slugName is kept as it can only be one particular slugName\n this.slugName = segmentName\n // nextSegment is overwritten to [] so that it can later be sorted specifically\n nextSegment = '[]'\n }\n }\n\n // If this UrlNode doesn't have the nextSegment yet we create a new child UrlNode\n if (!this.children.has(nextSegment)) {\n this.children.set(nextSegment, new UrlNode())\n }\n\n this.children\n .get(nextSegment)!\n ._insert(urlPaths.slice(1), slugNames, isCatchAll)\n }\n}\n\n/**\n * @deprecated Use `sortSortableRoutes` or `sortPages` instead.\n */\nexport function getSortedRoutes(\n normalizedPages: ReadonlyArray\n): string[] {\n // First the UrlNode is created, and every UrlNode can have only 1 dynamic segment\n // Eg you can't have pages/[post]/abc.js and pages/[hello]/something-else.js\n // Only 1 dynamic segment per nesting level\n\n // So in the case that is test/e2e/dynamic-routing it'll be this:\n // pages/[post]/comments.js\n // pages/blog/[post]/comment/[id].js\n // Both are fine because `pages/[post]` and `pages/blog` are on the same level\n // So in this case `UrlNode` created here has `this.slugName === 'post'`\n // And since your PR passed through `slugName` as an array basically it'd including it in too many possibilities\n // Instead what has to be passed through is the upwards path's dynamic names\n const root = new UrlNode()\n\n // Here the `root` gets injected multiple paths, and insert will break them up into sublevels\n normalizedPages.forEach((pagePath) => root.insert(pagePath))\n // Smoosh will then sort those sublevels up to the point where you get the correct route definition priority\n return root.smoosh()\n}\n\n/**\n * @deprecated Use `sortSortableRouteObjects` or `sortPageObjects` instead.\n */\nexport function getSortedRouteObjects(\n objects: T[],\n getter: (obj: T) => string\n): T[] {\n // We're assuming here that all the pathnames are unique, that way we can\n // sort the list and use the index as the key.\n const indexes: Record = {}\n const pathnames: string[] = []\n for (let i = 0; i < objects.length; i++) {\n const pathname = getter(objects[i])\n indexes[pathname] = i\n pathnames[i] = pathname\n }\n\n // Sort the pathnames.\n const sorted = getSortedRoutes(pathnames)\n\n // Map the sorted pathnames back to the original objects using the new sorted\n // index.\n return sorted.map((pathname) => objects[indexes[pathname]])\n}\n"],"names":["getSortedRouteObjects","getSortedRoutes","UrlNode","insert","urlPath","_insert","split","filter","Boolean","smoosh","_smoosh","prefix","childrenPaths","children","keys","sort","slugName","splice","indexOf","restSlugName","optionalRestSlugName","routes","map","c","get","reduce","prev","curr","push","placeholder","r","slice","Error","unshift","urlPaths","slugNames","isCatchAll","length","nextSegment","startsWith","endsWith","segmentName","isOptional","substring","handleSlug","previousSlug","nextSlug","forEach","slug","replace","has","set","Map","normalizedPages","root","pagePath","objects","getter","indexes","pathnames","i","pathname","sorted"],"mappings":";;;;;;;;;;;;;;;IAuOgBA,qBAAqB;eAArBA;;IAzBAC,eAAe;eAAfA;;;AA9MhB,MAAMC;IAOJC,OAAOC,OAAe,EAAQ;QAC5B,IAAI,CAACC,OAAO,CAACD,QAAQE,KAAK,CAAC,KAAKC,MAAM,CAACC,UAAU,EAAE,EAAE;IACvD;IAEAC,SAAmB;QACjB,OAAO,IAAI,CAACC,OAAO;IACrB;IAEQA,QAAQC,SAAiB,GAAG,EAAY;QAC9C,MAAMC,gBAAgB;eAAI,IAAI,CAACC,QAAQ,CAACC,IAAI;SAAG,CAACC,IAAI;QACpD,IAAI,IAAI,CAACC,QAAQ,KAAK,MAAM;YAC1BJ,cAAcK,MAAM,CAACL,cAAcM,OAAO,CAAC,OAAO;QACpD;QACA,IAAI,IAAI,CAACC,YAAY,KAAK,MAAM;YAC9BP,cAAcK,MAAM,CAACL,cAAcM,OAAO,CAAC,UAAU;QACvD;QACA,IAAI,IAAI,CAACE,oBAAoB,KAAK,MAAM;YACtCR,cAAcK,MAAM,CAACL,cAAcM,OAAO,CAAC,YAAY;QACzD;QAEA,MAAMG,SAAST,cACZU,GAAG,CAAC,CAACC,IAAM,IAAI,CAACV,QAAQ,CAACW,GAAG,CAACD,GAAIb,OAAO,CAAC,GAAGC,SAASY,EAAE,CAAC,CAAC,GACzDE,MAAM,CAAC,CAACC,MAAMC,OAAS;mBAAID;mBAASC;aAAK,EAAE,EAAE;QAEhD,IAAI,IAAI,CAACX,QAAQ,KAAK,MAAM;YAC1BK,OAAOO,IAAI,IACN,IAAI,CAACf,QAAQ,CAACW,GAAG,CAAC,MAAOd,OAAO,CAAC,GAAGC,OAAO,CAAC,EAAE,IAAI,CAACK,QAAQ,CAAC,EAAE,CAAC;QAEtE;QAEA,IAAI,CAAC,IAAI,CAACa,WAAW,EAAE;YACrB,MAAMC,IAAInB,WAAW,MAAM,MAAMA,OAAOoB,KAAK,CAAC,GAAG,CAAC;YAClD,IAAI,IAAI,CAACX,oBAAoB,IAAI,MAAM;gBACrC,MAAM,IAAIY,MACR,CAAC,oFAAoF,EAAEF,EAAE,OAAO,EAAEA,EAAE,KAAK,EAAE,IAAI,CAACV,oBAAoB,CAAC,KAAK,CAAC;YAE/I;YAEAC,OAAOY,OAAO,CAACH;QACjB;QAEA,IAAI,IAAI,CAACX,YAAY,KAAK,MAAM;YAC9BE,OAAOO,IAAI,IACN,IAAI,CAACf,QAAQ,CACbW,GAAG,CAAC,SACJd,OAAO,CAAC,GAAGC,OAAO,IAAI,EAAE,IAAI,CAACQ,YAAY,CAAC,EAAE,CAAC;QAEpD;QAEA,IAAI,IAAI,CAACC,oBAAoB,KAAK,MAAM;YACtCC,OAAOO,IAAI,IACN,IAAI,CAACf,QAAQ,CACbW,GAAG,CAAC,WACJd,OAAO,CAAC,GAAGC,OAAO,KAAK,EAAE,IAAI,CAACS,oBAAoB,CAAC,GAAG,CAAC;QAE9D;QAEA,OAAOC;IACT;IAEQhB,QACN6B,QAAkB,EAClBC,SAAmB,EACnBC,UAAmB,EACb;QACN,IAAIF,SAASG,MAAM,KAAK,GAAG;YACzB,IAAI,CAACR,WAAW,GAAG;YACnB;QACF;QAEA,IAAIO,YAAY;YACd,MAAM,IAAIJ,MAAM,CAAC,2CAA2C,CAAC;QAC/D;QAEA,wCAAwC;QACxC,IAAIM,cAAcJ,QAAQ,CAAC,EAAE;QAE7B,6CAA6C;QAC7C,IAAII,YAAYC,UAAU,CAAC,QAAQD,YAAYE,QAAQ,CAAC,MAAM;YAC5D,8CAA8C;YAC9C,IAAIC,cAAcH,YAAYP,KAAK,CAAC,GAAG,CAAC;YAExC,IAAIW,aAAa;YACjB,IAAID,YAAYF,UAAU,CAAC,QAAQE,YAAYD,QAAQ,CAAC,MAAM;gBAC5D,uDAAuD;gBACvDC,cAAcA,YAAYV,KAAK,CAAC,GAAG,CAAC;gBACpCW,aAAa;YACf;YAEA,IAAID,YAAYF,UAAU,CAAC,MAAM;gBAC/B,MAAM,IAAIP,MACR,CAAC,0CAA0C,EAAES,YAAY,yBAAyB,CAAC;YAEvF;YAEA,IAAIA,YAAYF,UAAU,CAAC,QAAQ;gBACjC,wCAAwC;gBACxCE,cAAcA,YAAYE,SAAS,CAAC;gBACpCP,aAAa;YACf;YAEA,IAAIK,YAAYF,UAAU,CAAC,QAAQE,YAAYD,QAAQ,CAAC,MAAM;gBAC5D,MAAM,IAAIR,MACR,CAAC,yDAAyD,EAAES,YAAY,GAAG,CAAC;YAEhF;YAEA,IAAIA,YAAYF,UAAU,CAAC,MAAM;gBAC/B,MAAM,IAAIP,MACR,CAAC,qDAAqD,EAAES,YAAY,GAAG,CAAC;YAE5E;YAEA,SAASG,WAAWC,YAA2B,EAAEC,QAAgB;gBAC/D,IAAID,iBAAiB,MAAM;oBACzB,6EAA6E;oBAC7E,iCAAiC;oBACjC,wBAAwB;oBACxB,sBAAsB;oBACtB,wFAAwF;oBACxF,IAAIA,iBAAiBC,UAAU;wBAC7B,wHAAwH;wBACxH,MAAM,IAAId,MACR,CAAC,gEAAgE,EAAEa,aAAa,OAAO,EAAEC,SAAS,GAAG,CAAC;oBAE1G;gBACF;gBAEAX,UAAUY,OAAO,CAAC,CAACC;oBACjB,IAAIA,SAASF,UAAU;wBACrB,MAAM,IAAId,MACR,CAAC,oCAAoC,EAAEc,SAAS,qCAAqC,CAAC;oBAE1F;oBAEA,IAAIE,KAAKC,OAAO,CAAC,OAAO,QAAQX,YAAYW,OAAO,CAAC,OAAO,KAAK;wBAC9D,MAAM,IAAIjB,MACR,CAAC,gCAAgC,EAAEgB,KAAK,OAAO,EAAEF,SAAS,8DAA8D,CAAC;oBAE7H;gBACF;gBAEAX,UAAUP,IAAI,CAACkB;YACjB;YAEA,IAAIV,YAAY;gBACd,IAAIM,YAAY;oBACd,IAAI,IAAI,CAACvB,YAAY,IAAI,MAAM;wBAC7B,MAAM,IAAIa,MACR,CAAC,qFAAqF,EAAE,IAAI,CAACb,YAAY,CAAC,QAAQ,EAAEe,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC;oBAEzI;oBAEAU,WAAW,IAAI,CAACxB,oBAAoB,EAAEqB;oBACtC,6DAA6D;oBAC7D,IAAI,CAACrB,oBAAoB,GAAGqB;oBAC5B,oFAAoF;oBACpFH,cAAc;gBAChB,OAAO;oBACL,IAAI,IAAI,CAAClB,oBAAoB,IAAI,MAAM;wBACrC,MAAM,IAAIY,MACR,CAAC,sFAAsF,EAAE,IAAI,CAACZ,oBAAoB,CAAC,SAAS,EAAEc,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC;oBAElJ;oBAEAU,WAAW,IAAI,CAACzB,YAAY,EAAEsB;oBAC9B,6DAA6D;oBAC7D,IAAI,CAACtB,YAAY,GAAGsB;oBACpB,kFAAkF;oBAClFH,cAAc;gBAChB;YACF,OAAO;gBACL,IAAII,YAAY;oBACd,MAAM,IAAIV,MACR,CAAC,kDAAkD,EAAEE,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC;gBAEzE;gBACAU,WAAW,IAAI,CAAC5B,QAAQ,EAAEyB;gBAC1B,6DAA6D;gBAC7D,IAAI,CAACzB,QAAQ,GAAGyB;gBAChB,+EAA+E;gBAC/EH,cAAc;YAChB;QACF;QAEA,iFAAiF;QACjF,IAAI,CAAC,IAAI,CAACzB,QAAQ,CAACqC,GAAG,CAACZ,cAAc;YACnC,IAAI,CAACzB,QAAQ,CAACsC,GAAG,CAACb,aAAa,IAAIpC;QACrC;QAEA,IAAI,CAACW,QAAQ,CACVW,GAAG,CAACc,aACJjC,OAAO,CAAC6B,SAASH,KAAK,CAAC,IAAII,WAAWC;IAC3C;;aAvMAP,cAAuB;aACvBhB,WAAiC,IAAIuC;aACrCpC,WAA0B;aAC1BG,eAA8B;aAC9BC,uBAAsC;;AAoMxC;AAKO,SAASnB,gBACdoD,eAAsC;IAEtC,kFAAkF;IAClF,4EAA4E;IAC5E,2CAA2C;IAE3C,iEAAiE;IACjE,2BAA2B;IAC3B,oCAAoC;IACpC,8EAA8E;IAC9E,wEAAwE;IACxE,gHAAgH;IAChH,4EAA4E;IAC5E,MAAMC,OAAO,IAAIpD;IAEjB,6FAA6F;IAC7FmD,gBAAgBN,OAAO,CAAC,CAACQ,WAAaD,KAAKnD,MAAM,CAACoD;IAClD,4GAA4G;IAC5G,OAAOD,KAAK7C,MAAM;AACpB;AAKO,SAAST,sBACdwD,OAAY,EACZC,MAA0B;IAE1B,yEAAyE;IACzE,8CAA8C;IAC9C,MAAMC,UAAkC,CAAC;IACzC,MAAMC,YAAsB,EAAE;IAC9B,IAAK,IAAIC,IAAI,GAAGA,IAAIJ,QAAQnB,MAAM,EAAEuB,IAAK;QACvC,MAAMC,WAAWJ,OAAOD,OAAO,CAACI,EAAE;QAClCF,OAAO,CAACG,SAAS,GAAGD;QACpBD,SAAS,CAACC,EAAE,GAAGC;IACjB;IAEA,sBAAsB;IACtB,MAAMC,SAAS7D,gBAAgB0D;IAE/B,6EAA6E;IAC7E,SAAS;IACT,OAAOG,OAAOxC,GAAG,CAAC,CAACuC,WAAaL,OAAO,CAACE,OAAO,CAACG,SAAS,CAAC;AAC5D","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.d.ts b/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..29b25dc89a225e085d529d7e1c149f0b5b812140 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.d.ts @@ -0,0 +1,230 @@ +/** + * The transport format for RSC responses. + * + * Every type in this module is prefixed with `Transport` to distinguish the + * wire format from client-local types (`Segment`, `RouteTree`, `CacheNode`, + * `FlightRouterState`). Client code converts out of Transport types at the + * decode boundary and never stores them. + * + * A response carries a single tree, anchored at the root segment, where each + * node has both its identity and (optionally) its render output. Partial + * responses are expressed per node: the convention across the format is that + * absence means "nothing here" — an omitted `d` means the segment was not + * rendered as part of the response, an omitted slot key means the response + * carries no information about that slot. + */ +import type React from 'react'; +import type { DynamicParamTypesShort, FlightRouterState, Segment } from './app-router-types'; +import type { VaryParamsIterable } from './segment-cache/vary-params-decoding'; +/** + * Segment identity on the wire. A string for static segments; an object for + * dynamic (parameterized) segments. + * + * Page segments are always `__PAGE__`. The search params are sent separately, + * in the response's `q` field. + */ +export type TransportSegment = string | TransportDynamicSegment; +export type TransportDynamicSegment = { + /** name — the param name, e.g. 'id' for [id] */ + n: string; + /** type — dynamic param type */ + t: DynamicParamTypesShort; + /** + * key — the param value / cache key. null when the client is expected to + * parse the value from the URL itself, which keeps the response cacheable + * across param values. + */ + k: string | null; + /** siblings — static sibling segments at this URL level; null = unknown */ + s: readonly string[] | null; +}; +/** + * Render output for a single segment. Grouped into one object so a node's + * "rendered vs skipped" state is a single presence check. Also used for the + * head (metadata/viewport), which is output without structure. + * + * `r` may be null: the segment was skipped — the response acknowledges its + * position without rendering anything for it, e.g. a shared layout the + * client is expected to already have. This is distinct from `d` being absent + * on the node, which means the response makes no claim about the segment's + * output at all (the client should fetch it lazily if it doesn't have it). + */ +export type TransportSegmentData = { + /** rsc — the React node for this segment; null = skipped (not rendered) */ + r: React.ReactNode; + /** + * isPartial — whether anything in the segment's output is not fully + * resolved: dynamic holes, runtime holes, anything suspended. + * + * Navigation responses carry a plain boolean, known at render time. It is + * a render-wide constant (isPossiblyPartialResponse in + * create-component-tree.tsx), identical on every node and only + * conservatively accurate, so the client resolves a boolean-form node's + * actual partiality from the response-level signal instead (see + * decodeTransportNode). + * + * Per-segment prefetch responses carry the rewindable promise encoding + * instead: fulfilled = complete, pending forever = partial. Partiality is + * only discovered there by probing the buffered prerender (a partial + * segment's probe never resolves, the same way Flight encodes the holes + * themselves), and the encoding must survive the client's shell + * double-decode — the response buffer is decoded a second time truncated + * at the shell byte boundary (`a`), and a fulfillment row that landed past + * the boundary must read as "partial" in that decode. The promise form is + * only ever read off a fully-buffered decode's thenable status. + */ + p: boolean | Promise; + /** + * varyParams — an iterable of the route params this segment's output + * depends on (one name per yield, deduped). Used by the client router to + * determine cache key specificity: segments that only access certain + * params can be reused across navigations where unaccessed params change. + * + * Does NOT include root params; those are emitted once at the response + * level (`r` on the response wrapper) and unioned in by the consumer. + * + * - null: tracking was not enabled for this render (e.g., not a + * prerender). Treat conservatively — assume all params vary. + * - Drains to empty: segment accesses no params (e.g., client components, + * or server components that don't read params). Can be shared across + * all param values. + * - Drains to non-empty: segment depends on those params. Can only be + * reused when those specific params match. + */ + v: VaryParamsIterable | null; + /** + * staleTime in seconds — present only in per-segment prefetch responses, + * where staleness is tracked per node. Navigation responses carry + * staleness at the response level instead (the wrapper's `s` iterable or + * the Next-Router-Stale-Time header). + * + * An async iterable rather than a plain number because the final value is + * only known late in the stream, and the iterable form survives a + * truncated/rewound shell decode (read via thenable status from the + * buffered response). The client takes the last yielded value. + */ + s?: AsyncIterable; +}; +/** + * Structure of a segment node, independent of whether render output + * is attached. Shared by both response variants. + */ +type TransportNodeShape = { + /** segment — identity */ + s: TransportSegment; + /** hints — PrefetchHint bitmask; omitted when zero or unknown */ + h?: number; +}; +/** + * A node in a FULL response tree: every node carries data, and slot maps are + * exhaustive. Produced by full renders: the initial document payload and + * error payloads. "Full" means the response accounts for every node — there + * is nothing for the client to fetch lazily. Data-level holes + * (`d.p === true`) and skipped nodes (`d.r === null`) are still possible. + */ +export type FullTransportNode = TransportNodeShape & { + /** data — always present in a full tree */ + d: TransportSegmentData; + /** + * children — parallel routes; omitted for leaf segments. A Map rather + * than a plain object because slot names are app-defined; with a plain + * object, every distinct combination of slot names creates a different + * hidden class, making keyed access megamorphic. + */ + c?: Map; +}; +/** + * A node in a PARTIAL response tree: produced by navigations, refreshes, and + * actions — anywhere the server diffs against client state or renders a + * subset of the route. + * + * The client treats the response as an overlay over its current tree: + * + * - A node present in the tree is authoritative for that position's identity. + * - `d` present: the response accounts for this segment. Its output is `d.r`, + * which may be null when the segment was skipped — not rendered because + * the client already has it (e.g. a shared layout). + * - `d` omitted: the response makes no claim about this segment's output. + * The client keeps what it has, or lazily fetches when it renders (e.g. + * segments beneath a loading boundary in a non-PPR prefetch). + * - A slot key omitted from `c` (or `c` omitted): on a skipped node + * (`d.r === null`), the response carries no information about that slot + * and the client keeps its subtree untouched. On any other node the + * subtree is authoritative, so an omitted slot is simply absent. + * - `h` omitted: on a skipped node, the client keeps its existing hints for + * the segment; on any other node it means the hints are zero. + * + * The client's cache write descends through nodes with `d` omitted (see + * writeTreeDataIntoCache), so data may appear at any depth below a no-claim + * node — the identity spine of a per-segment prefetch response is the + * canonical producer of that shape. + */ +export type PartialTransportNode = TransportNodeShape & { + /** data — omitted when this segment was not rendered in this response */ + d?: TransportSegmentData; + /** children — omitted field or key = no information about those slots */ + c?: Map; +}; +/** + * Shared type for code that walks either variant. Note: FullTransportNode is + * structurally assignable to PartialTransportNode, so this union collapses + * to PartialTransportNode for the type checker; the union spelling + * documents intent. + */ +export type TransportNode = FullTransportNode | PartialTransportNode; +/** + * The tree + head bundle of a response. + */ +export type FullTransportData = { + /** tree */ + t: FullTransportNode; + /** head — always present and complete in a full response */ + h: TransportSegmentData; +}; +export type PartialTransportData = { + t: PartialTransportNode; + /** omitted = this response carries no head (e.g. router-state-only responses) */ + h?: TransportSegmentData; +}; +export type TransportData = FullTransportData | PartialTransportData; +/** + * Creates the data for a skipped segment: a null `r` marks the position as + * acknowledged by the response, with no output attached (see the note on + * TransportSegmentData). Used by producers for the segments along the path + * from the root down to the rendered subtrees. + */ +export declare function createSkippedSegmentData(): TransportSegmentData; +/** + * Reads a late-resolving value from a fully-buffered Flight decode via the + * thenable's status. Flight sets `status`/`value` on a row's promise once + * its bytes are processed, and a buffered decode processes every byte + * synchronously, so any row that made it into the payload is readable + * without awaiting. Returns `unresolvedValue` for a row that is pending or + * absent in this decode — e.g. one whose fulfillment landed past a + * truncated shell decode's boundary; that's what scopes a response's + * late-resolving signals to the payload being decoded. Returns + * `rejectedValue` (defaults to `unresolvedValue`) for a rejected row — an + * aborted render errors rows that were still pending when it happened. + * + * Shared by client and server: the client reads buffered prefetch + * responses; the server (collect-segment-data) reads the buffered page + * payload it re-serializes into per-segment responses. + */ +export declare function readFulfilledValue(valueFromServer: PromiseLike, unresolvedValue: TFallback, rejectedValue?: T | TFallback): T | TFallback; +/** + * Converts a segment's client/server-internal representation to its wire + * representation. + */ +export declare function segmentToTransportSegment(segment: Segment): TransportSegment; +/** + * Converts a segment's wire representation to the client/server-internal + * `Segment` type. + */ +export declare function transportSegmentToSegment(transportSegment: TransportSegment): Segment; +/** + * Derives a FlightRouterState from a transport tree. Used where the client + * needs a router-state representation of a full response (e.g. the initial + * hydration payload). Render output (`d`) is not carried over. + */ +export declare function transportNodeToFlightRouterState(node: TransportNode, renderedSearch: string): FlightRouterState; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.js b/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.js new file mode 100644 index 0000000000000000000000000000000000000000..272ca32d62d95a027dde0f7bfebd25e13151d2f1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createSkippedSegmentData: null, + readFulfilledValue: null, + segmentToTransportSegment: null, + transportNodeToFlightRouterState: null, + transportSegmentToSegment: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createSkippedSegmentData: function() { + return createSkippedSegmentData; + }, + readFulfilledValue: function() { + return readFulfilledValue; + }, + segmentToTransportSegment: function() { + return segmentToTransportSegment; + }, + transportNodeToFlightRouterState: function() { + return transportNodeToFlightRouterState; + }, + transportSegmentToSegment: function() { + return transportSegmentToSegment; + } +}); +const _segment = require("./segment"); +function createSkippedSegmentData() { + return { + r: null, + p: true, + v: null + }; +} +function readFulfilledValue(valueFromServer, unresolvedValue, rejectedValue = unresolvedValue) { + const thenable = valueFromServer; + // Force Flight to unwrap a received-but-not-yet-settled row. + thenable.then(noop, noop); + switch(thenable.status){ + case 'fulfilled': + return thenable.value; + case 'rejected': + return rejectedValue; + // No status yet: the row is still pending, or absent from this decode. + case undefined: + default: + return unresolvedValue; + } +} +const noop = ()=>{}; +function segmentToTransportSegment(segment) { + if (typeof segment === 'string') { + return segment; + } + return { + n: segment[0], + t: segment[2], + k: segment[1], + s: segment[3] + }; +} +function transportSegmentToSegment(transportSegment) { + if (typeof transportSegment === 'string') { + return transportSegment; + } + return [ + transportSegment.n, + // `k` may be null when the client is expected to parse the param value + // from the URL (per-segment prefetch responses). Callers that need the + // real value resolve it from the rendered pathname instead of using this + // function (see resolveTransportSegment in decode-server-response); the + // remaining callers are value-insensitive (segment request keys, which + // never include param values) or only see concrete keys. + transportSegment.k ?? '', + transportSegment.t, + transportSegment.s + ]; +} +function transportNodeToFlightRouterState(node, renderedSearch) { + const parallelRoutes = {}; + const children = node.c; + if (children !== undefined) { + for (const [parallelRouteKey, childNode] of children){ + parallelRoutes[parallelRouteKey] = transportNodeToFlightRouterState(childNode, renderedSearch); + } + } + const flightRouterState = [ + transportSegmentToSegment(node.s), + parallelRoutes + ]; + if (node.h !== undefined) { + flightRouterState[4] = node.h; + } + if (flightRouterState[0] === _segment.PAGE_SEGMENT_KEY) { + flightRouterState[5] = renderedSearch; + } + return flightRouterState; +} + +//# sourceMappingURL=rsc-transport.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.js.map b/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.js.map new file mode 100644 index 0000000000000000000000000000000000000000..262b0f5b65363c6dfb1f1c652d59cabc4aacae71 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/rsc-transport.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/rsc-transport.ts"],"sourcesContent":["import { PAGE_SEGMENT_KEY } from './segment'\n/**\n * The transport format for RSC responses.\n *\n * Every type in this module is prefixed with `Transport` to distinguish the\n * wire format from client-local types (`Segment`, `RouteTree`, `CacheNode`,\n * `FlightRouterState`). Client code converts out of Transport types at the\n * decode boundary and never stores them.\n *\n * A response carries a single tree, anchored at the root segment, where each\n * node has both its identity and (optionally) its render output. Partial\n * responses are expressed per node: the convention across the format is that\n * absence means \"nothing here\" — an omitted `d` means the segment was not\n * rendered as part of the response, an omitted slot key means the response\n * carries no information about that slot.\n */\n\nimport type React from 'react'\nimport type {\n DynamicParamTypesShort,\n FlightRouterState,\n Segment,\n} from './app-router-types'\nimport type { VaryParamsIterable } from './segment-cache/vary-params-decoding'\n\n/**\n * Segment identity on the wire. A string for static segments; an object for\n * dynamic (parameterized) segments.\n *\n * Page segments are always `__PAGE__`. The search params are sent separately,\n * in the response's `q` field.\n */\nexport type TransportSegment = string | TransportDynamicSegment\n\nexport type TransportDynamicSegment = {\n /** name — the param name, e.g. 'id' for [id] */\n n: string\n /** type — dynamic param type */\n t: DynamicParamTypesShort\n /**\n * key — the param value / cache key. null when the client is expected to\n * parse the value from the URL itself, which keeps the response cacheable\n * across param values.\n */\n k: string | null\n /** siblings — static sibling segments at this URL level; null = unknown */\n s: readonly string[] | null\n}\n\n/**\n * Render output for a single segment. Grouped into one object so a node's\n * \"rendered vs skipped\" state is a single presence check. Also used for the\n * head (metadata/viewport), which is output without structure.\n *\n * `r` may be null: the segment was skipped — the response acknowledges its\n * position without rendering anything for it, e.g. a shared layout the\n * client is expected to already have. This is distinct from `d` being absent\n * on the node, which means the response makes no claim about the segment's\n * output at all (the client should fetch it lazily if it doesn't have it).\n */\nexport type TransportSegmentData = {\n /** rsc — the React node for this segment; null = skipped (not rendered) */\n r: React.ReactNode\n /**\n * isPartial — whether anything in the segment's output is not fully\n * resolved: dynamic holes, runtime holes, anything suspended.\n *\n * Navigation responses carry a plain boolean, known at render time. It is\n * a render-wide constant (isPossiblyPartialResponse in\n * create-component-tree.tsx), identical on every node and only\n * conservatively accurate, so the client resolves a boolean-form node's\n * actual partiality from the response-level signal instead (see\n * decodeTransportNode).\n *\n * Per-segment prefetch responses carry the rewindable promise encoding\n * instead: fulfilled = complete, pending forever = partial. Partiality is\n * only discovered there by probing the buffered prerender (a partial\n * segment's probe never resolves, the same way Flight encodes the holes\n * themselves), and the encoding must survive the client's shell\n * double-decode — the response buffer is decoded a second time truncated\n * at the shell byte boundary (`a`), and a fulfillment row that landed past\n * the boundary must read as \"partial\" in that decode. The promise form is\n * only ever read off a fully-buffered decode's thenable status.\n */\n p: boolean | Promise\n /**\n * varyParams — an iterable of the route params this segment's output\n * depends on (one name per yield, deduped). Used by the client router to\n * determine cache key specificity: segments that only access certain\n * params can be reused across navigations where unaccessed params change.\n *\n * Does NOT include root params; those are emitted once at the response\n * level (`r` on the response wrapper) and unioned in by the consumer.\n *\n * - null: tracking was not enabled for this render (e.g., not a\n * prerender). Treat conservatively — assume all params vary.\n * - Drains to empty: segment accesses no params (e.g., client components,\n * or server components that don't read params). Can be shared across\n * all param values.\n * - Drains to non-empty: segment depends on those params. Can only be\n * reused when those specific params match.\n */\n v: VaryParamsIterable | null\n /**\n * staleTime in seconds — present only in per-segment prefetch responses,\n * where staleness is tracked per node. Navigation responses carry\n * staleness at the response level instead (the wrapper's `s` iterable or\n * the Next-Router-Stale-Time header).\n *\n * An async iterable rather than a plain number because the final value is\n * only known late in the stream, and the iterable form survives a\n * truncated/rewound shell decode (read via thenable status from the\n * buffered response). The client takes the last yielded value.\n */\n s?: AsyncIterable\n}\n\n/**\n * Structure of a segment node, independent of whether render output\n * is attached. Shared by both response variants.\n */\ntype TransportNodeShape = {\n /** segment — identity */\n s: TransportSegment\n /** hints — PrefetchHint bitmask; omitted when zero or unknown */\n h?: number\n}\n\n/**\n * A node in a FULL response tree: every node carries data, and slot maps are\n * exhaustive. Produced by full renders: the initial document payload and\n * error payloads. \"Full\" means the response accounts for every node — there\n * is nothing for the client to fetch lazily. Data-level holes\n * (`d.p === true`) and skipped nodes (`d.r === null`) are still possible.\n */\nexport type FullTransportNode = TransportNodeShape & {\n /** data — always present in a full tree */\n d: TransportSegmentData\n /**\n * children — parallel routes; omitted for leaf segments. A Map rather\n * than a plain object because slot names are app-defined; with a plain\n * object, every distinct combination of slot names creates a different\n * hidden class, making keyed access megamorphic.\n */\n c?: Map\n}\n\n/**\n * A node in a PARTIAL response tree: produced by navigations, refreshes, and\n * actions — anywhere the server diffs against client state or renders a\n * subset of the route.\n *\n * The client treats the response as an overlay over its current tree:\n *\n * - A node present in the tree is authoritative for that position's identity.\n * - `d` present: the response accounts for this segment. Its output is `d.r`,\n * which may be null when the segment was skipped — not rendered because\n * the client already has it (e.g. a shared layout).\n * - `d` omitted: the response makes no claim about this segment's output.\n * The client keeps what it has, or lazily fetches when it renders (e.g.\n * segments beneath a loading boundary in a non-PPR prefetch).\n * - A slot key omitted from `c` (or `c` omitted): on a skipped node\n * (`d.r === null`), the response carries no information about that slot\n * and the client keeps its subtree untouched. On any other node the\n * subtree is authoritative, so an omitted slot is simply absent.\n * - `h` omitted: on a skipped node, the client keeps its existing hints for\n * the segment; on any other node it means the hints are zero.\n *\n * The client's cache write descends through nodes with `d` omitted (see\n * writeTreeDataIntoCache), so data may appear at any depth below a no-claim\n * node — the identity spine of a per-segment prefetch response is the\n * canonical producer of that shape.\n */\nexport type PartialTransportNode = TransportNodeShape & {\n /** data — omitted when this segment was not rendered in this response */\n d?: TransportSegmentData\n /** children — omitted field or key = no information about those slots */\n c?: Map\n}\n\n/**\n * Shared type for code that walks either variant. Note: FullTransportNode is\n * structurally assignable to PartialTransportNode, so this union collapses\n * to PartialTransportNode for the type checker; the union spelling\n * documents intent.\n */\nexport type TransportNode = FullTransportNode | PartialTransportNode\n\n/**\n * The tree + head bundle of a response.\n */\nexport type FullTransportData = {\n /** tree */\n t: FullTransportNode\n /** head — always present and complete in a full response */\n h: TransportSegmentData\n}\n\nexport type PartialTransportData = {\n t: PartialTransportNode\n /** omitted = this response carries no head (e.g. router-state-only responses) */\n h?: TransportSegmentData\n}\n\nexport type TransportData = FullTransportData | PartialTransportData\n\n/**\n * Creates the data for a skipped segment: a null `r` marks the position as\n * acknowledged by the response, with no output attached (see the note on\n * TransportSegmentData). Used by producers for the segments along the path\n * from the root down to the rendered subtrees.\n */\nexport function createSkippedSegmentData(): TransportSegmentData {\n return { r: null, p: true, v: null }\n}\n\n/**\n * Reads a late-resolving value from a fully-buffered Flight decode via the\n * thenable's status. Flight sets `status`/`value` on a row's promise once\n * its bytes are processed, and a buffered decode processes every byte\n * synchronously, so any row that made it into the payload is readable\n * without awaiting. Returns `unresolvedValue` for a row that is pending or\n * absent in this decode — e.g. one whose fulfillment landed past a\n * truncated shell decode's boundary; that's what scopes a response's\n * late-resolving signals to the payload being decoded. Returns\n * `rejectedValue` (defaults to `unresolvedValue`) for a rejected row — an\n * aborted render errors rows that were still pending when it happened.\n *\n * Shared by client and server: the client reads buffered prefetch\n * responses; the server (collect-segment-data) reads the buffered page\n * payload it re-serializes into per-segment responses.\n */\nexport function readFulfilledValue(\n valueFromServer: PromiseLike,\n unresolvedValue: TFallback,\n rejectedValue: T | TFallback = unresolvedValue\n): T | TFallback {\n const thenable = valueFromServer as PromiseLike & {\n status?: string\n value?: T\n }\n // Force Flight to unwrap a received-but-not-yet-settled row.\n thenable.then(noop, noop)\n switch (thenable.status) {\n case 'fulfilled':\n return thenable.value as T\n case 'rejected':\n return rejectedValue\n // No status yet: the row is still pending, or absent from this decode.\n case undefined:\n default:\n return unresolvedValue\n }\n}\n\nconst noop = () => {}\n\n/**\n * Converts a segment's client/server-internal representation to its wire\n * representation.\n */\nexport function segmentToTransportSegment(segment: Segment): TransportSegment {\n if (typeof segment === 'string') {\n return segment\n }\n return {\n n: segment[0],\n t: segment[2],\n k: segment[1],\n s: segment[3],\n }\n}\n\n/**\n * Converts a segment's wire representation to the client/server-internal\n * `Segment` type.\n */\nexport function transportSegmentToSegment(\n transportSegment: TransportSegment\n): Segment {\n if (typeof transportSegment === 'string') {\n return transportSegment\n }\n return [\n transportSegment.n,\n // `k` may be null when the client is expected to parse the param value\n // from the URL (per-segment prefetch responses). Callers that need the\n // real value resolve it from the rendered pathname instead of using this\n // function (see resolveTransportSegment in decode-server-response); the\n // remaining callers are value-insensitive (segment request keys, which\n // never include param values) or only see concrete keys.\n transportSegment.k ?? '',\n transportSegment.t,\n transportSegment.s,\n ]\n}\n\n/**\n * Derives a FlightRouterState from a transport tree. Used where the client\n * needs a router-state representation of a full response (e.g. the initial\n * hydration payload). Render output (`d`) is not carried over.\n */\nexport function transportNodeToFlightRouterState(\n node: TransportNode,\n renderedSearch: string\n): FlightRouterState {\n const parallelRoutes: Record = {}\n const children = node.c\n if (children !== undefined) {\n for (const [parallelRouteKey, childNode] of children) {\n parallelRoutes[parallelRouteKey] = transportNodeToFlightRouterState(\n childNode,\n renderedSearch\n )\n }\n }\n const flightRouterState: FlightRouterState = [\n transportSegmentToSegment(node.s),\n parallelRoutes,\n ]\n if (node.h !== undefined) {\n flightRouterState[4] = node.h\n }\n if (flightRouterState[0] === PAGE_SEGMENT_KEY) {\n flightRouterState[5] = renderedSearch\n }\n return flightRouterState\n}\n"],"names":["createSkippedSegmentData","readFulfilledValue","segmentToTransportSegment","transportNodeToFlightRouterState","transportSegmentToSegment","r","p","v","valueFromServer","unresolvedValue","rejectedValue","thenable","then","noop","status","value","undefined","segment","n","t","k","s","transportSegment","node","renderedSearch","parallelRoutes","children","c","parallelRouteKey","childNode","flightRouterState","h","PAGE_SEGMENT_KEY"],"mappings":";;;;;;;;;;;;;;;;;;IAoNgBA,wBAAwB;eAAxBA;;IAoBAC,kBAAkB;eAAlBA;;IA6BAC,yBAAyB;eAAzBA;;IAyCAC,gCAAgC;eAAhCA;;IAzBAC,yBAAyB;eAAzBA;;;yBArRiB;AAoN1B,SAASJ;IACd,OAAO;QAAEK,GAAG;QAAMC,GAAG;QAAMC,GAAG;IAAK;AACrC;AAkBO,SAASN,mBACdO,eAA+B,EAC/BC,eAA0B,EAC1BC,gBAA+BD,eAAe;IAE9C,MAAME,WAAWH;IAIjB,6DAA6D;IAC7DG,SAASC,IAAI,CAACC,MAAMA;IACpB,OAAQF,SAASG,MAAM;QACrB,KAAK;YACH,OAAOH,SAASI,KAAK;QACvB,KAAK;YACH,OAAOL;QACT,uEAAuE;QACvE,KAAKM;QACL;YACE,OAAOP;IACX;AACF;AAEA,MAAMI,OAAO,KAAO;AAMb,SAASX,0BAA0Be,OAAgB;IACxD,IAAI,OAAOA,YAAY,UAAU;QAC/B,OAAOA;IACT;IACA,OAAO;QACLC,GAAGD,OAAO,CAAC,EAAE;QACbE,GAAGF,OAAO,CAAC,EAAE;QACbG,GAAGH,OAAO,CAAC,EAAE;QACbI,GAAGJ,OAAO,CAAC,EAAE;IACf;AACF;AAMO,SAASb,0BACdkB,gBAAkC;IAElC,IAAI,OAAOA,qBAAqB,UAAU;QACxC,OAAOA;IACT;IACA,OAAO;QACLA,iBAAiBJ,CAAC;QAClB,uEAAuE;QACvE,uEAAuE;QACvE,yEAAyE;QACzE,wEAAwE;QACxE,uEAAuE;QACvE,yDAAyD;QACzDI,iBAAiBF,CAAC,IAAI;QACtBE,iBAAiBH,CAAC;QAClBG,iBAAiBD,CAAC;KACnB;AACH;AAOO,SAASlB,iCACdoB,IAAmB,EACnBC,cAAsB;IAEtB,MAAMC,iBAAoD,CAAC;IAC3D,MAAMC,WAAWH,KAAKI,CAAC;IACvB,IAAID,aAAaV,WAAW;QAC1B,KAAK,MAAM,CAACY,kBAAkBC,UAAU,IAAIH,SAAU;YACpDD,cAAc,CAACG,iBAAiB,GAAGzB,iCACjC0B,WACAL;QAEJ;IACF;IACA,MAAMM,oBAAuC;QAC3C1B,0BAA0BmB,KAAKF,CAAC;QAChCI;KACD;IACD,IAAIF,KAAKQ,CAAC,KAAKf,WAAW;QACxBc,iBAAiB,CAAC,EAAE,GAAGP,KAAKQ,CAAC;IAC/B;IACA,IAAID,iBAAiB,CAAC,EAAE,KAAKE,yBAAgB,EAAE;QAC7CF,iBAAiB,CAAC,EAAE,GAAGN;IACzB;IACA,OAAOM;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.d.ts b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0846f127f813ca5746b15eb9e777a0b6f3d25df --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.d.ts @@ -0,0 +1,12 @@ +import type { Segment as FlightRouterStateSegment } from '../app-router-types'; +type Opaque = T & { + __brand: K; +}; +export type SegmentRequestKeyPart = Opaque<'SegmentRequestKeyPart', string>; +export type SegmentRequestKey = Opaque<'SegmentRequestKey', string>; +export declare const ROOT_SEGMENT_REQUEST_KEY: SegmentRequestKey; +export declare const HEAD_REQUEST_KEY: SegmentRequestKey; +export declare function createSegmentRequestKeyPart(segment: FlightRouterStateSegment): SegmentRequestKeyPart; +export declare function appendSegmentRequestKeyPart(parentRequestKey: SegmentRequestKey, parallelRouteKey: string, childRequestKeyPart: SegmentRequestKeyPart): SegmentRequestKey; +export declare function convertSegmentPathToStaticExportFilename(segmentPath: string): string; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.js b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.js new file mode 100644 index 0000000000000000000000000000000000000000..e83d95df3d3405b681251ef5fa040649ae2e5842 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.js @@ -0,0 +1,86 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + HEAD_REQUEST_KEY: null, + ROOT_SEGMENT_REQUEST_KEY: null, + appendSegmentRequestKeyPart: null, + convertSegmentPathToStaticExportFilename: null, + createSegmentRequestKeyPart: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + HEAD_REQUEST_KEY: function() { + return HEAD_REQUEST_KEY; + }, + ROOT_SEGMENT_REQUEST_KEY: function() { + return ROOT_SEGMENT_REQUEST_KEY; + }, + appendSegmentRequestKeyPart: function() { + return appendSegmentRequestKeyPart; + }, + convertSegmentPathToStaticExportFilename: function() { + return convertSegmentPathToStaticExportFilename; + }, + createSegmentRequestKeyPart: function() { + return createSegmentRequestKeyPart; + } +}); +const ROOT_SEGMENT_REQUEST_KEY = ''; +const HEAD_REQUEST_KEY = '/_head'; +function createSegmentRequestKeyPart(segment) { + if (typeof segment === 'string') { + const safeName = // TODO: FlightRouterState encodes Not Found routes as "/_not-found". + // But params typically don't include the leading slash. We should use + // a different encoding to avoid this special case. + segment === '/_not-found' ? '_not-found' : encodeToFilesystemAndURLSafeString(segment); + // Since this is not a dynamic segment, it's fully encoded. It does not + // need to be "hydrated" with a param value. + return safeName; + } + const name = segment[0]; + const paramType = segment[2]; + const safeName = encodeToFilesystemAndURLSafeString(name); + const encodedName = '$' + paramType + '$' + safeName; + return encodedName; +} +function appendSegmentRequestKeyPart(parentRequestKey, parallelRouteKey, childRequestKeyPart) { + // Aside from being filesystem safe, segment keys are also designed so that + // each segment and parallel route creates its own subdirectory. Roughly in + // the same shape as the source app directory. This is mostly just for easier + // debugging (you can open up the build folder and navigate the output); if + // we wanted to do we could just use a flat structure. + // Omit the parallel route key for children, since this is the most + // common case. Saves some bytes (and it's what the app directory does). + const slotKey = parallelRouteKey === 'children' ? childRequestKeyPart : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childRequestKeyPart}`; + return parentRequestKey + '/' + slotKey; +} +// Define a regex pattern to match the most common characters found in a route +// param. It excludes anything that might not be cross-platform filesystem +// compatible, like |. It does not need to be precise because the fallback is to +// just base64url-encode the whole parameter, which is fine; we just don't do it +// by default for compactness, and for easier debugging. +const simpleParamValueRegex = /^[a-zA-Z0-9\-_@]+$/; +function encodeToFilesystemAndURLSafeString(value) { + if (simpleParamValueRegex.test(value)) { + return value; + } + // If there are any unsafe characters, base64url-encode the entire value. + // We also add a ! prefix so it doesn't collide with the simple case. + const base64url = btoa(value).replace(/\+/g, '-') // Replace '+' with '-' + .replace(/\//g, '_') // Replace '/' with '_' + .replace(/=+$/, '') // Remove trailing '=' + ; + return '!' + base64url; +} +function convertSegmentPathToStaticExportFilename(segmentPath) { + return `__next${segmentPath.replace(/\//g, '.')}.txt`; +} + +//# sourceMappingURL=segment-value-encoding.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.js.map b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c36092ec53c7979d52f06dffd25c86d29acef64c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/segment-cache/segment-value-encoding.ts"],"sourcesContent":["import type { Segment as FlightRouterStateSegment } from '../app-router-types'\n\n// TypeScript trick to simulate opaque types, like in Flow.\ntype Opaque = T & { __brand: K }\n\nexport type SegmentRequestKeyPart = Opaque<'SegmentRequestKeyPart', string>\nexport type SegmentRequestKey = Opaque<'SegmentRequestKey', string>\n\nexport const ROOT_SEGMENT_REQUEST_KEY = '' as SegmentRequestKey\n\nexport const HEAD_REQUEST_KEY = '/_head' as SegmentRequestKey\n\nexport function createSegmentRequestKeyPart(\n segment: FlightRouterStateSegment\n): SegmentRequestKeyPart {\n if (typeof segment === 'string') {\n const safeName =\n // TODO: FlightRouterState encodes Not Found routes as \"/_not-found\".\n // But params typically don't include the leading slash. We should use\n // a different encoding to avoid this special case.\n segment === '/_not-found'\n ? '_not-found'\n : encodeToFilesystemAndURLSafeString(segment)\n // Since this is not a dynamic segment, it's fully encoded. It does not\n // need to be \"hydrated\" with a param value.\n return safeName as SegmentRequestKeyPart\n }\n\n const name = segment[0]\n const paramType = segment[2]\n const safeName = encodeToFilesystemAndURLSafeString(name)\n\n const encodedName = '$' + paramType + '$' + safeName\n return encodedName as SegmentRequestKeyPart\n}\n\nexport function appendSegmentRequestKeyPart(\n parentRequestKey: SegmentRequestKey,\n parallelRouteKey: string,\n childRequestKeyPart: SegmentRequestKeyPart\n): SegmentRequestKey {\n // Aside from being filesystem safe, segment keys are also designed so that\n // each segment and parallel route creates its own subdirectory. Roughly in\n // the same shape as the source app directory. This is mostly just for easier\n // debugging (you can open up the build folder and navigate the output); if\n // we wanted to do we could just use a flat structure.\n\n // Omit the parallel route key for children, since this is the most\n // common case. Saves some bytes (and it's what the app directory does).\n const slotKey =\n parallelRouteKey === 'children'\n ? childRequestKeyPart\n : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childRequestKeyPart}`\n return (parentRequestKey + '/' + slotKey) as SegmentRequestKey\n}\n\n// Define a regex pattern to match the most common characters found in a route\n// param. It excludes anything that might not be cross-platform filesystem\n// compatible, like |. It does not need to be precise because the fallback is to\n// just base64url-encode the whole parameter, which is fine; we just don't do it\n// by default for compactness, and for easier debugging.\nconst simpleParamValueRegex = /^[a-zA-Z0-9\\-_@]+$/\n\nfunction encodeToFilesystemAndURLSafeString(value: string) {\n if (simpleParamValueRegex.test(value)) {\n return value\n }\n // If there are any unsafe characters, base64url-encode the entire value.\n // We also add a ! prefix so it doesn't collide with the simple case.\n const base64url = btoa(value)\n .replace(/\\+/g, '-') // Replace '+' with '-'\n .replace(/\\//g, '_') // Replace '/' with '_'\n .replace(/=+$/, '') // Remove trailing '='\n return '!' + base64url\n}\n\nexport function convertSegmentPathToStaticExportFilename(\n segmentPath: string\n): string {\n return `__next${segmentPath.replace(/\\//g, '.')}.txt`\n}\n"],"names":["HEAD_REQUEST_KEY","ROOT_SEGMENT_REQUEST_KEY","appendSegmentRequestKeyPart","convertSegmentPathToStaticExportFilename","createSegmentRequestKeyPart","segment","safeName","encodeToFilesystemAndURLSafeString","name","paramType","encodedName","parentRequestKey","parallelRouteKey","childRequestKeyPart","slotKey","simpleParamValueRegex","value","test","base64url","btoa","replace","segmentPath"],"mappings":";;;;;;;;;;;;;;;;;;IAUaA,gBAAgB;eAAhBA;;IAFAC,wBAAwB;eAAxBA;;IA4BGC,2BAA2B;eAA3BA;;IAwCAC,wCAAwC;eAAxCA;;IAhEAC,2BAA2B;eAA3BA;;;AAJT,MAAMH,2BAA2B;AAEjC,MAAMD,mBAAmB;AAEzB,SAASI,4BACdC,OAAiC;IAEjC,IAAI,OAAOA,YAAY,UAAU;QAC/B,MAAMC,WACJ,qEAAqE;QACrE,sEAAsE;QACtE,mDAAmD;QACnDD,YAAY,gBACR,eACAE,mCAAmCF;QACzC,uEAAuE;QACvE,4CAA4C;QAC5C,OAAOC;IACT;IAEA,MAAME,OAAOH,OAAO,CAAC,EAAE;IACvB,MAAMI,YAAYJ,OAAO,CAAC,EAAE;IAC5B,MAAMC,WAAWC,mCAAmCC;IAEpD,MAAME,cAAc,MAAMD,YAAY,MAAMH;IAC5C,OAAOI;AACT;AAEO,SAASR,4BACdS,gBAAmC,EACnCC,gBAAwB,EACxBC,mBAA0C;IAE1C,2EAA2E;IAC3E,2EAA2E;IAC3E,6EAA6E;IAC7E,2EAA2E;IAC3E,sDAAsD;IAEtD,mEAAmE;IACnE,wEAAwE;IACxE,MAAMC,UACJF,qBAAqB,aACjBC,sBACA,CAAC,CAAC,EAAEN,mCAAmCK,kBAAkB,CAAC,EAAEC,qBAAqB;IACvF,OAAQF,mBAAmB,MAAMG;AACnC;AAEA,8EAA8E;AAC9E,0EAA0E;AAC1E,gFAAgF;AAChF,gFAAgF;AAChF,wDAAwD;AACxD,MAAMC,wBAAwB;AAE9B,SAASR,mCAAmCS,KAAa;IACvD,IAAID,sBAAsBE,IAAI,CAACD,QAAQ;QACrC,OAAOA;IACT;IACA,yEAAyE;IACzE,qEAAqE;IACrE,MAAME,YAAYC,KAAKH,OACpBI,OAAO,CAAC,OAAO,KAAK,uBAAuB;KAC3CA,OAAO,CAAC,OAAO,KAAK,uBAAuB;KAC3CA,OAAO,CAAC,OAAO,IAAI,sBAAsB;;IAC5C,OAAO,MAAMF;AACf;AAEO,SAASf,yCACdkB,WAAmB;IAEnB,OAAO,CAAC,MAAM,EAAEA,YAAYD,OAAO,CAAC,OAAO,KAAK,IAAI,CAAC;AACvD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.d.ts b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c094be16186eb684e4ce4aafe1ce81784f0c299 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.d.ts @@ -0,0 +1,74 @@ +/** + * Vary Params Decoding + * + * This module is shared between server and client. + */ +/** + * The vary path id for search params. Path params are identified by their + * name. Search params don't have a fixed set of names, so any access to them + * is reported under this one id, and the segment is keyed by the whole search + * string (see createVaryingSearchParams in app-render/vary-params.ts). + * + * It's a number so it can't collide with a param name. `app/[?]/page.tsx` is a + * valid route. + */ +export declare const SEARCH_PARAMS_VARY_ID = 0; +export type VaryParamId = string | number; +/** + * The params a piece of rendered output depends on — the ids of the vary path + * nodes it read: path param names, and SEARCH_PARAMS_VARY_ID for the search + * params — as the source that reports them rather than a snapshot of it. + * + * The wire iterables can only be drained from a fully-buffered response; they + * are drained once at decode into an already-settled thenable, and read at the + * point a decision needs the set (readVaryParams). + */ +export type VaryParams = PromiseLike>; +/** + * Vary params are serialized into the Flight stream as an + * `AsyncIterable` that yields each accessed param id exactly once + * (the server dedupes before emitting). Because each access is flushed into the + * stream as it happens, there's no step at the end of the render that has to + * run for the client to read anything. If a prerender is aborted by sync I/O, + * the params yielded before the abort are already in the stream, and they're + * exactly the params the partial response actually depends on. + * + * Root params are NOT included in a segment's own iterable. They're emitted + * once at the top level of the response (as a separate iterable) and unioned in + * by `decodeVaryParams`, because root params can be accessed at any point + * during the render — folding them into every segment would otherwise require + * a merge once the whole render is complete. + */ +export type VaryParamsIterable = AsyncIterable; +/** + * Converts a segment's (or the head's) vary params off the wire, at the + * decode boundary, unioning in the response-level root params. + * + * Root params are emitted once at the top level rather than folded into every + * segment by the server, so every decode recombines them here — building the + * merge into the decode means a caller can't forget it, and it's done in a + * single pass with no intermediate set. + * + * Returns null ("unknown", key on all params) unless BOTH iterables are + * present. A null/absent `iterable` means the segment's own tracking wasn't + * enabled (e.g. not a prerender). A null/absent `rootIterable` means root + * params weren't tracked — and since a segment's own iterable never includes + * root params (those are accessed in layouts above it), narrowing on the + * segment set alone would wrongly assume no root params were accessed. In + * either case we stay conservative. + * + * When both are present each is authoritative even when it drains to the empty + * set — a tracked segment that read no params, with no root params accessed, + * can be shared across all param values. + */ +export declare function decodeVaryParams(iterable: VaryParamsIterable | null | undefined, rootIterable: VaryParamsIterable | null | undefined): VaryParams | null; +/** + * Wraps an already-known set as a vary params source. Shaped like a settled + * Flight promise so readVaryParams can read it off the thenable's status. + */ +export declare function createVaryParams(total: Set): VaryParams; +/** + * Reads the set from a vary params source. Null when it is not available; + * the reader assumes every param varies. + */ +export declare function readVaryParams(varyParams: VaryParams): Set | null; diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.js b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.js new file mode 100644 index 0000000000000000000000000000000000000000..bb04424855e8a6c7acf153567aee4f2886e6a6ab --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.js @@ -0,0 +1,87 @@ +/** + * Vary Params Decoding + * + * This module is shared between server and client. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + SEARCH_PARAMS_VARY_ID: null, + createVaryParams: null, + decodeVaryParams: null, + readVaryParams: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + SEARCH_PARAMS_VARY_ID: function() { + return SEARCH_PARAMS_VARY_ID; + }, + createVaryParams: function() { + return createVaryParams; + }, + decodeVaryParams: function() { + return decodeVaryParams; + }, + readVaryParams: function() { + return readVaryParams; + } +}); +const _rsctransport = require("../rsc-transport"); +const SEARCH_PARAMS_VARY_ID = 0; +/** + * Synchronously drains a vary params `AsyncIterable`, adding each yielded name + * to `target`. + * + * By the time this runs (on the client, or in collectSegmentData), the Flight + * stream has been fully buffered, so every yielded value is already + * materialized and can be read without awaiting: each iterator result is a + * Flight chunk whose settled state `readFulfilledValue` reads off the + * thenable's status. + * + * We add "every param yielded up to the point the stream suspends": a + * normally-closed iterable drains fully, while one left hanging (a sync-I/O + * abort, or a `close()` whose row hasn't flushed yet) drains to the prefix + * already in the stream. Both are correct — a segment's param accesses are all + * flushed as they happen during its render, so the prefix is exactly the set + * the response depends on. We therefore never need the terminating `done` row + * to be present; it's only stream hygiene. + */ function drainVaryParams(iterable, target) { + const iterator = iterable[Symbol.asyncIterator](); + while(true){ + const step = (0, _rsctransport.readFulfilledValue)(iterator.next(), undefined); + if (step === undefined || step.done) { + // Either the stream suspended here — everything yielded before this + // point has already been added — or the iterable finished cleanly. + return; + } + target.add(step.value); + } +} +function decodeVaryParams(iterable, rootIterable) { + if (iterable === null || iterable === undefined || rootIterable === null || rootIterable === undefined) { + return null; + } + const total = new Set(); + drainVaryParams(iterable, total); + drainVaryParams(rootIterable, total); + return createVaryParams(total); +} +function createVaryParams(total) { + // TODO: Don't need to use a native promise. Just inline a thenable that + // immediately calls its listener. + const settled = Promise.resolve(total); + settled.status = 'fulfilled'; + settled.value = total; + return settled; +} +function readVaryParams(varyParams) { + return (0, _rsctransport.readFulfilledValue)(varyParams, null); +} + +//# sourceMappingURL=vary-params-decoding.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.js.map b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2fa4c39beb65fd4d95ad3e13b66bb5920ddad578 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment-cache/vary-params-decoding.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/segment-cache/vary-params-decoding.ts"],"sourcesContent":["/**\n * Vary Params Decoding\n *\n * This module is shared between server and client.\n */\n\nimport { readFulfilledValue } from '../rsc-transport'\n\n/**\n * The vary path id for search params. Path params are identified by their\n * name. Search params don't have a fixed set of names, so any access to them\n * is reported under this one id, and the segment is keyed by the whole search\n * string (see createVaryingSearchParams in app-render/vary-params.ts).\n *\n * It's a number so it can't collide with a param name. `app/[?]/page.tsx` is a\n * valid route.\n */\nexport const SEARCH_PARAMS_VARY_ID = 0\n\n// Path param names, and SEARCH_PARAMS_VARY_ID for the search params.\nexport type VaryParamId = string | number\n\n/**\n * The params a piece of rendered output depends on — the ids of the vary path\n * nodes it read: path param names, and SEARCH_PARAMS_VARY_ID for the search\n * params — as the source that reports them rather than a snapshot of it.\n *\n * The wire iterables can only be drained from a fully-buffered response; they\n * are drained once at decode into an already-settled thenable, and read at the\n * point a decision needs the set (readVaryParams).\n */\nexport type VaryParams = PromiseLike>\n\n/**\n * Vary params are serialized into the Flight stream as an\n * `AsyncIterable` that yields each accessed param id exactly once\n * (the server dedupes before emitting). Because each access is flushed into the\n * stream as it happens, there's no step at the end of the render that has to\n * run for the client to read anything. If a prerender is aborted by sync I/O,\n * the params yielded before the abort are already in the stream, and they're\n * exactly the params the partial response actually depends on.\n *\n * Root params are NOT included in a segment's own iterable. They're emitted\n * once at the top level of the response (as a separate iterable) and unioned in\n * by `decodeVaryParams`, because root params can be accessed at any point\n * during the render — folding them into every segment would otherwise require\n * a merge once the whole render is complete.\n */\nexport type VaryParamsIterable = AsyncIterable\n\n/**\n * Synchronously drains a vary params `AsyncIterable`, adding each yielded name\n * to `target`.\n *\n * By the time this runs (on the client, or in collectSegmentData), the Flight\n * stream has been fully buffered, so every yielded value is already\n * materialized and can be read without awaiting: each iterator result is a\n * Flight chunk whose settled state `readFulfilledValue` reads off the\n * thenable's status.\n *\n * We add \"every param yielded up to the point the stream suspends\": a\n * normally-closed iterable drains fully, while one left hanging (a sync-I/O\n * abort, or a `close()` whose row hasn't flushed yet) drains to the prefix\n * already in the stream. Both are correct — a segment's param accesses are all\n * flushed as they happen during its render, so the prefix is exactly the set\n * the response depends on. We therefore never need the terminating `done` row\n * to be present; it's only stream hygiene.\n */\nfunction drainVaryParams(\n iterable: VaryParamsIterable,\n target: Set\n): void {\n const iterator = iterable[Symbol.asyncIterator]()\n while (true) {\n const step = readFulfilledValue(iterator.next(), undefined)\n if (step === undefined || step.done) {\n // Either the stream suspended here — everything yielded before this\n // point has already been added — or the iterable finished cleanly.\n return\n }\n target.add(step.value)\n }\n}\n\n/**\n * Converts a segment's (or the head's) vary params off the wire, at the\n * decode boundary, unioning in the response-level root params.\n *\n * Root params are emitted once at the top level rather than folded into every\n * segment by the server, so every decode recombines them here — building the\n * merge into the decode means a caller can't forget it, and it's done in a\n * single pass with no intermediate set.\n *\n * Returns null (\"unknown\", key on all params) unless BOTH iterables are\n * present. A null/absent `iterable` means the segment's own tracking wasn't\n * enabled (e.g. not a prerender). A null/absent `rootIterable` means root\n * params weren't tracked — and since a segment's own iterable never includes\n * root params (those are accessed in layouts above it), narrowing on the\n * segment set alone would wrongly assume no root params were accessed. In\n * either case we stay conservative.\n *\n * When both are present each is authoritative even when it drains to the empty\n * set — a tracked segment that read no params, with no root params accessed,\n * can be shared across all param values.\n */\nexport function decodeVaryParams(\n iterable: VaryParamsIterable | null | undefined,\n rootIterable: VaryParamsIterable | null | undefined\n): VaryParams | null {\n if (\n iterable === null ||\n iterable === undefined ||\n rootIterable === null ||\n rootIterable === undefined\n ) {\n return null\n }\n const total: Set = new Set()\n drainVaryParams(iterable, total)\n drainVaryParams(rootIterable, total)\n return createVaryParams(total)\n}\n\n/**\n * Wraps an already-known set as a vary params source. Shaped like a settled\n * Flight promise so readVaryParams can read it off the thenable's status.\n */\nexport function createVaryParams(total: Set): VaryParams {\n // TODO: Don't need to use a native promise. Just inline a thenable that\n // immediately calls its listener.\n const settled = Promise.resolve(total) as Promise> & {\n status: 'fulfilled'\n value: Set\n }\n settled.status = 'fulfilled'\n settled.value = total\n return settled\n}\n\n/**\n * Reads the set from a vary params source. Null when it is not available;\n * the reader assumes every param varies.\n */\nexport function readVaryParams(\n varyParams: VaryParams\n): Set | null {\n return readFulfilledValue(varyParams, null)\n}\n"],"names":["SEARCH_PARAMS_VARY_ID","createVaryParams","decodeVaryParams","readVaryParams","drainVaryParams","iterable","target","iterator","Symbol","asyncIterator","step","readFulfilledValue","next","undefined","done","add","value","rootIterable","total","Set","settled","Promise","resolve","status","varyParams"],"mappings":"AAAA;;;;CAIC;;;;;;;;;;;;;;;;;IAaYA,qBAAqB;eAArBA;;IA8GGC,gBAAgB;eAAhBA;;IAtBAC,gBAAgB;eAAhBA;;IAsCAC,cAAc;eAAdA;;;8BAzImB;AAW5B,MAAMH,wBAAwB;AAiCrC;;;;;;;;;;;;;;;;;CAiBC,GACD,SAASI,gBACPC,QAA4B,EAC5BC,MAAwB;IAExB,MAAMC,WAAWF,QAAQ,CAACG,OAAOC,aAAa,CAAC;IAC/C,MAAO,KAAM;QACX,MAAMC,OAAOC,IAAAA,gCAAkB,EAACJ,SAASK,IAAI,IAAIC;QACjD,IAAIH,SAASG,aAAaH,KAAKI,IAAI,EAAE;YACnC,oEAAoE;YACpE,mEAAmE;YACnE;QACF;QACAR,OAAOS,GAAG,CAACL,KAAKM,KAAK;IACvB;AACF;AAuBO,SAASd,iBACdG,QAA+C,EAC/CY,YAAmD;IAEnD,IACEZ,aAAa,QACbA,aAAaQ,aACbI,iBAAiB,QACjBA,iBAAiBJ,WACjB;QACA,OAAO;IACT;IACA,MAAMK,QAA0B,IAAIC;IACpCf,gBAAgBC,UAAUa;IAC1Bd,gBAAgBa,cAAcC;IAC9B,OAAOjB,iBAAiBiB;AAC1B;AAMO,SAASjB,iBAAiBiB,KAAuB;IACtD,wEAAwE;IACxE,kCAAkC;IAClC,MAAME,UAAUC,QAAQC,OAAO,CAACJ;IAIhCE,QAAQG,MAAM,GAAG;IACjBH,QAAQJ,KAAK,GAAGE;IAChB,OAAOE;AACT;AAMO,SAASjB,eACdqB,UAAsB;IAEtB,OAAOb,IAAAA,gCAAkB,EAACa,YAAY;AACxC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment.d.ts b/e-commerce/node_modules/next/dist/shared/lib/segment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9bd98ce54c2690f361ae070f68490463c7b4381 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment.d.ts @@ -0,0 +1,10 @@ +import type { FlightRouterState, Segment } from './app-router-types'; +export declare function getSegmentValue(segment: Segment): string; +export declare function isGroupSegment(segment: string): boolean; +export declare function isParallelRouteSegment(segment: string): boolean; +export declare function computeSelectedLayoutSegment(segments: string[] | null, parallelRouteKey: string): string | null; +/** Get the canonical parameters from the current level to the leaf node. */ +export declare function getSelectedLayoutSegmentPath(tree: FlightRouterState, parallelRouteKey: string, first?: boolean, segmentPath?: string[]): string[]; +export declare const PAGE_SEGMENT_KEY = "__PAGE__"; +export declare const DEFAULT_SEGMENT_KEY = "__DEFAULT__"; +export declare const NOT_FOUND_SEGMENT_KEY = "/_not-found"; diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment.js b/e-commerce/node_modules/next/dist/shared/lib/segment.js new file mode 100644 index 0000000000000000000000000000000000000000..35a9fce933e8f85b3c6a783ccc18d2a7df8130c2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DEFAULT_SEGMENT_KEY: null, + NOT_FOUND_SEGMENT_KEY: null, + PAGE_SEGMENT_KEY: null, + computeSelectedLayoutSegment: null, + getSegmentValue: null, + getSelectedLayoutSegmentPath: null, + isGroupSegment: null, + isParallelRouteSegment: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DEFAULT_SEGMENT_KEY: function() { + return DEFAULT_SEGMENT_KEY; + }, + NOT_FOUND_SEGMENT_KEY: function() { + return NOT_FOUND_SEGMENT_KEY; + }, + PAGE_SEGMENT_KEY: function() { + return PAGE_SEGMENT_KEY; + }, + computeSelectedLayoutSegment: function() { + return computeSelectedLayoutSegment; + }, + getSegmentValue: function() { + return getSegmentValue; + }, + getSelectedLayoutSegmentPath: function() { + return getSelectedLayoutSegmentPath; + }, + isGroupSegment: function() { + return isGroupSegment; + }, + isParallelRouteSegment: function() { + return isParallelRouteSegment; + } +}); +function getSegmentValue(segment) { + return Array.isArray(segment) ? segment[1] : segment; +} +function isGroupSegment(segment) { + // Use array[0] for performant purpose + return segment[0] === '(' && segment.endsWith(')'); +} +function isParallelRouteSegment(segment) { + return segment.startsWith('@') && segment !== '@children'; +} +function computeSelectedLayoutSegment(segments, parallelRouteKey) { + if (!segments || segments.length === 0) { + return null; + } + // For 'children', use first segment; for other parallel routes, use last segment + const rawSegment = parallelRouteKey === 'children' ? segments[0] : segments[segments.length - 1]; + // If the default slot is showing, return null since it's not technically "selected" (it's a fallback) + // Returning an internal value like `__DEFAULT__` would be confusing + return rawSegment === DEFAULT_SEGMENT_KEY ? null : rawSegment; +} +function getSelectedLayoutSegmentPath(tree, parallelRouteKey, first = true, segmentPath = []) { + let node; + if (first) { + // Use the provided parallel route key on the first parallel route + node = tree[1][parallelRouteKey]; + } else { + // After first parallel route prefer children, if there's no children pick the first parallel route. + const parallelRoutes = tree[1]; + node = parallelRoutes.children ?? Object.values(parallelRoutes)[0]; + } + if (!node) return segmentPath; + const segment = node[0]; + let segmentValue = getSegmentValue(segment); + if (!segmentValue || segmentValue === PAGE_SEGMENT_KEY) { + return segmentPath; + } + segmentPath.push(segmentValue); + return getSelectedLayoutSegmentPath(node, parallelRouteKey, false, segmentPath); +} +const PAGE_SEGMENT_KEY = '__PAGE__'; +const DEFAULT_SEGMENT_KEY = '__DEFAULT__'; +const NOT_FOUND_SEGMENT_KEY = '/_not-found'; + +//# sourceMappingURL=segment.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/segment.js.map b/e-commerce/node_modules/next/dist/shared/lib/segment.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f8e63cfd6320162a3eb5e1f8adf51ef81afda576 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/segment.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/segment.ts"],"sourcesContent":["import type { FlightRouterState, Segment } from './app-router-types'\n\nexport function getSegmentValue(segment: Segment) {\n return Array.isArray(segment) ? segment[1] : segment\n}\n\nexport function isGroupSegment(segment: string) {\n // Use array[0] for performant purpose\n return segment[0] === '(' && segment.endsWith(')')\n}\n\nexport function isParallelRouteSegment(segment: string) {\n return segment.startsWith('@') && segment !== '@children'\n}\n\nexport function computeSelectedLayoutSegment(\n segments: string[] | null,\n parallelRouteKey: string\n): string | null {\n if (!segments || segments.length === 0) {\n return null\n }\n\n // For 'children', use first segment; for other parallel routes, use last segment\n const rawSegment =\n parallelRouteKey === 'children'\n ? segments[0]\n : segments[segments.length - 1]\n\n // If the default slot is showing, return null since it's not technically \"selected\" (it's a fallback)\n // Returning an internal value like `__DEFAULT__` would be confusing\n return rawSegment === DEFAULT_SEGMENT_KEY ? null : rawSegment\n}\n\n/** Get the canonical parameters from the current level to the leaf node. */\nexport function getSelectedLayoutSegmentPath(\n tree: FlightRouterState,\n parallelRouteKey: string,\n first = true,\n segmentPath: string[] = []\n): string[] {\n let node: FlightRouterState\n if (first) {\n // Use the provided parallel route key on the first parallel route\n node = tree[1][parallelRouteKey]\n } else {\n // After first parallel route prefer children, if there's no children pick the first parallel route.\n const parallelRoutes = tree[1]\n node = parallelRoutes.children ?? Object.values(parallelRoutes)[0]\n }\n\n if (!node) return segmentPath\n const segment = node[0]\n\n let segmentValue = getSegmentValue(segment)\n\n if (!segmentValue || segmentValue === PAGE_SEGMENT_KEY) {\n return segmentPath\n }\n\n segmentPath.push(segmentValue)\n\n return getSelectedLayoutSegmentPath(\n node,\n parallelRouteKey,\n false,\n segmentPath\n )\n}\n\nexport const PAGE_SEGMENT_KEY = '__PAGE__'\nexport const DEFAULT_SEGMENT_KEY = '__DEFAULT__'\nexport const NOT_FOUND_SEGMENT_KEY = '/_not-found'\n"],"names":["DEFAULT_SEGMENT_KEY","NOT_FOUND_SEGMENT_KEY","PAGE_SEGMENT_KEY","computeSelectedLayoutSegment","getSegmentValue","getSelectedLayoutSegmentPath","isGroupSegment","isParallelRouteSegment","segment","Array","isArray","endsWith","startsWith","segments","parallelRouteKey","length","rawSegment","tree","first","segmentPath","node","parallelRoutes","children","Object","values","segmentValue","push"],"mappings":";;;;;;;;;;;;;;;;;;;;;IAuEaA,mBAAmB;eAAnBA;;IACAC,qBAAqB;eAArBA;;IAFAC,gBAAgB;eAAhBA;;IAvDGC,4BAA4B;eAA5BA;;IAbAC,eAAe;eAAfA;;IAiCAC,4BAA4B;eAA5BA;;IA7BAC,cAAc;eAAdA;;IAKAC,sBAAsB;eAAtBA;;;AATT,SAASH,gBAAgBI,OAAgB;IAC9C,OAAOC,MAAMC,OAAO,CAACF,WAAWA,OAAO,CAAC,EAAE,GAAGA;AAC/C;AAEO,SAASF,eAAeE,OAAe;IAC5C,sCAAsC;IACtC,OAAOA,OAAO,CAAC,EAAE,KAAK,OAAOA,QAAQG,QAAQ,CAAC;AAChD;AAEO,SAASJ,uBAAuBC,OAAe;IACpD,OAAOA,QAAQI,UAAU,CAAC,QAAQJ,YAAY;AAChD;AAEO,SAASL,6BACdU,QAAyB,EACzBC,gBAAwB;IAExB,IAAI,CAACD,YAAYA,SAASE,MAAM,KAAK,GAAG;QACtC,OAAO;IACT;IAEA,iFAAiF;IACjF,MAAMC,aACJF,qBAAqB,aACjBD,QAAQ,CAAC,EAAE,GACXA,QAAQ,CAACA,SAASE,MAAM,GAAG,EAAE;IAEnC,sGAAsG;IACtG,oEAAoE;IACpE,OAAOC,eAAehB,sBAAsB,OAAOgB;AACrD;AAGO,SAASX,6BACdY,IAAuB,EACvBH,gBAAwB,EACxBI,QAAQ,IAAI,EACZC,cAAwB,EAAE;IAE1B,IAAIC;IACJ,IAAIF,OAAO;QACT,kEAAkE;QAClEE,OAAOH,IAAI,CAAC,EAAE,CAACH,iBAAiB;IAClC,OAAO;QACL,oGAAoG;QACpG,MAAMO,iBAAiBJ,IAAI,CAAC,EAAE;QAC9BG,OAAOC,eAAeC,QAAQ,IAAIC,OAAOC,MAAM,CAACH,eAAe,CAAC,EAAE;IACpE;IAEA,IAAI,CAACD,MAAM,OAAOD;IAClB,MAAMX,UAAUY,IAAI,CAAC,EAAE;IAEvB,IAAIK,eAAerB,gBAAgBI;IAEnC,IAAI,CAACiB,gBAAgBA,iBAAiBvB,kBAAkB;QACtD,OAAOiB;IACT;IAEAA,YAAYO,IAAI,CAACD;IAEjB,OAAOpB,6BACLe,MACAN,kBACA,OACAK;AAEJ;AAEO,MAAMjB,mBAAmB;AACzB,MAAMF,sBAAsB;AAC5B,MAAMC,wBAAwB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e834ff5d1cdda4b49b04980a418b9cb41ad6bb22 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.d.ts @@ -0,0 +1,4 @@ +import React from 'react'; +export type ServerInsertedHTMLHook = (callbacks: () => React.ReactNode) => void; +export declare const ServerInsertedHTMLContext: React.Context; +export declare function useServerInsertedHTML(callback: () => React.ReactNode): void; diff --git a/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..747713f3f3f91183b87a9f6aac1f400364a7ed70 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js @@ -0,0 +1,35 @@ +'use client'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ServerInsertedHTMLContext: null, + useServerInsertedHTML: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ServerInsertedHTMLContext: function() { + return ServerInsertedHTMLContext; + }, + useServerInsertedHTML: function() { + return useServerInsertedHTML; + } +}); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react")); +const ServerInsertedHTMLContext = /*#__PURE__*/ _react.default.createContext(null); +function useServerInsertedHTML(callback) { + const addInsertedServerHTMLCallback = (0, _react.useContext)(ServerInsertedHTMLContext); + // Should have no effects on client where there's no flush effects provider + if (addInsertedServerHTMLCallback) { + addInsertedServerHTMLCallback(callback); + } +} + +//# sourceMappingURL=server-inserted-html.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..77a1fda26233db97db7438107421f163d9e51b05 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/server-inserted-html.shared-runtime.tsx"],"sourcesContent":["'use client'\n\nimport React, { useContext } from 'react'\n\nexport type ServerInsertedHTMLHook = (callbacks: () => React.ReactNode) => void\n\n// Use `React.createContext` to avoid errors from the RSC checks because\n// it can't be imported directly in Server Components:\n//\n// import { createContext } from 'react'\n//\n// More info: https://github.com/vercel/next.js/pull/40686\nexport const ServerInsertedHTMLContext =\n React.createContext(null as any)\n\nexport function useServerInsertedHTML(callback: () => React.ReactNode): void {\n const addInsertedServerHTMLCallback = useContext(ServerInsertedHTMLContext)\n // Should have no effects on client where there's no flush effects provider\n if (addInsertedServerHTMLCallback) {\n addInsertedServerHTMLCallback(callback)\n }\n}\n"],"names":["ServerInsertedHTMLContext","useServerInsertedHTML","React","createContext","callback","addInsertedServerHTMLCallback","useContext"],"mappings":"AAAA;;;;;;;;;;;;;;;;IAYaA,yBAAyB;eAAzBA;;IAGGC,qBAAqB;eAArBA;;;;iEAbkB;AAU3B,MAAMD,0CACXE,cAAK,CAACC,aAAa,CAAgC;AAE9C,SAASF,sBAAsBG,QAA+B;IACnE,MAAMC,gCAAgCC,IAAAA,iBAAU,EAACN;IACjD,2EAA2E;IAC3E,IAAIK,+BAA+B;QACjCA,8BAA8BD;IAChC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.d.ts b/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c36982751236d81ef0b1e4a1c5770b1ff94acb0e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.d.ts @@ -0,0 +1,33 @@ +export interface ServerReferenceInfo { + type: 'server-action' | 'use-cache'; + usedArgs: [boolean, boolean, boolean, boolean, boolean, boolean]; + hasRestArgs: boolean; +} +export declare const SERVER_REFERENCE_ID_LENGTH = 42; +export declare function mightBeServerReferenceId(id: string): boolean; +/** + * Extracts info about the server reference for the given server reference ID by + * parsing the first byte of the hex-encoded ID. + * + * ``` + * Bit positions: [7] [6] [5] [4] [3] [2] [1] [0] + * Bits: typeBit argMask restArgs + * ``` + * + * If the `typeBit` is `1` the server reference represents a `"use cache"` + * function, otherwise a server action. + * + * The `argMask` encodes whether the function uses the argument at the + * respective position. + * + * The `restArgs` bit indicates whether the function uses a rest parameter. It's + * also set to 1 if the function has more than 6 args. + * + * @param id hex-encoded server reference ID + */ +export declare function extractInfoFromServerReferenceId(id: string): ServerReferenceInfo; +/** + * Creates a sparse array containing only the used arguments based on the + * provided action info. + */ +export declare function omitUnusedArgs(args: unknown[], info: ServerReferenceInfo): unknown[]; diff --git a/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.js b/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.js new file mode 100644 index 0000000000000000000000000000000000000000..174e4c1829a4972266514a05ec3af88d0ba034ae --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + SERVER_REFERENCE_ID_LENGTH: null, + extractInfoFromServerReferenceId: null, + mightBeServerReferenceId: null, + omitUnusedArgs: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + SERVER_REFERENCE_ID_LENGTH: function() { + return SERVER_REFERENCE_ID_LENGTH; + }, + extractInfoFromServerReferenceId: function() { + return extractInfoFromServerReferenceId; + }, + mightBeServerReferenceId: function() { + return mightBeServerReferenceId; + }, + omitUnusedArgs: function() { + return omitUnusedArgs; + } +}); +const SERVER_REFERENCE_ID_LENGTH = 42; +function mightBeServerReferenceId(id) { + return id.length === SERVER_REFERENCE_ID_LENGTH; +} +function extractInfoFromServerReferenceId(id) { + const infoByte = parseInt(id.slice(0, 2), 16); + const typeBit = infoByte >> 7 & 0x1; + const argMask = infoByte >> 1 & 0x3f; + const restArgs = infoByte & 0x1; + const usedArgs = Array(6); + for(let index = 0; index < 6; index++){ + const bitPosition = 5 - index; + const bit = argMask >> bitPosition & 0x1; + usedArgs[index] = bit === 1; + } + return { + type: typeBit === 1 ? 'use-cache' : 'server-action', + usedArgs: usedArgs, + hasRestArgs: restArgs === 1 + }; +} +function omitUnusedArgs(args, info) { + const filteredArgs = new Array(args.length); + let length = 0; + for(let index = 0; index < args.length; index++){ + if (index < 6 && info.usedArgs[index] || // This assumes that the server reference info byte has the restArgs bit + // set to 1 if there are more than 6 args. + index >= 6 && info.hasRestArgs) { + filteredArgs[index] = args[index]; + length = index + 1; + } + } + // Trim trailing unused args from the array. + filteredArgs.length = length; + return filteredArgs; +} + +//# sourceMappingURL=server-reference-info.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.js.map b/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d5eb23c1b772a8b1d69b6ca93a7ff8d00583dc61 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/server-reference-info.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/server-reference-info.ts"],"sourcesContent":["export interface ServerReferenceInfo {\n type: 'server-action' | 'use-cache'\n usedArgs: [boolean, boolean, boolean, boolean, boolean, boolean]\n hasRestArgs: boolean\n}\n\nexport const SERVER_REFERENCE_ID_LENGTH = 42\n\nexport function mightBeServerReferenceId(id: string): boolean {\n return id.length === SERVER_REFERENCE_ID_LENGTH\n}\n\n/**\n * Extracts info about the server reference for the given server reference ID by\n * parsing the first byte of the hex-encoded ID.\n *\n * ```\n * Bit positions: [7] [6] [5] [4] [3] [2] [1] [0]\n * Bits: typeBit argMask restArgs\n * ```\n *\n * If the `typeBit` is `1` the server reference represents a `\"use cache\"`\n * function, otherwise a server action.\n *\n * The `argMask` encodes whether the function uses the argument at the\n * respective position.\n *\n * The `restArgs` bit indicates whether the function uses a rest parameter. It's\n * also set to 1 if the function has more than 6 args.\n *\n * @param id hex-encoded server reference ID\n */\nexport function extractInfoFromServerReferenceId(\n id: string\n): ServerReferenceInfo {\n const infoByte = parseInt(id.slice(0, 2), 16)\n const typeBit = (infoByte >> 7) & 0x1\n const argMask = (infoByte >> 1) & 0x3f\n const restArgs = infoByte & 0x1\n const usedArgs = Array(6)\n\n for (let index = 0; index < 6; index++) {\n const bitPosition = 5 - index\n const bit = (argMask >> bitPosition) & 0x1\n usedArgs[index] = bit === 1\n }\n\n return {\n type: typeBit === 1 ? 'use-cache' : 'server-action',\n usedArgs: usedArgs as [\n boolean,\n boolean,\n boolean,\n boolean,\n boolean,\n boolean,\n ],\n hasRestArgs: restArgs === 1,\n }\n}\n\n/**\n * Creates a sparse array containing only the used arguments based on the\n * provided action info.\n */\nexport function omitUnusedArgs(\n args: unknown[],\n info: ServerReferenceInfo\n): unknown[] {\n const filteredArgs = new Array(args.length)\n let length = 0\n\n for (let index = 0; index < args.length; index++) {\n if (\n (index < 6 && info.usedArgs[index]) ||\n // This assumes that the server reference info byte has the restArgs bit\n // set to 1 if there are more than 6 args.\n (index >= 6 && info.hasRestArgs)\n ) {\n filteredArgs[index] = args[index]\n length = index + 1\n }\n }\n\n // Trim trailing unused args from the array.\n filteredArgs.length = length\n\n return filteredArgs\n}\n"],"names":["SERVER_REFERENCE_ID_LENGTH","extractInfoFromServerReferenceId","mightBeServerReferenceId","omitUnusedArgs","id","length","infoByte","parseInt","slice","typeBit","argMask","restArgs","usedArgs","Array","index","bitPosition","bit","type","hasRestArgs","args","info","filteredArgs"],"mappings":";;;;;;;;;;;;;;;;;IAMaA,0BAA0B;eAA1BA;;IA0BGC,gCAAgC;eAAhCA;;IAxBAC,wBAAwB;eAAxBA;;IAyDAC,cAAc;eAAdA;;;AA3DT,MAAMH,6BAA6B;AAEnC,SAASE,yBAAyBE,EAAU;IACjD,OAAOA,GAAGC,MAAM,KAAKL;AACvB;AAsBO,SAASC,iCACdG,EAAU;IAEV,MAAME,WAAWC,SAASH,GAAGI,KAAK,CAAC,GAAG,IAAI;IAC1C,MAAMC,UAAU,AAACH,YAAY,IAAK;IAClC,MAAMI,UAAU,AAACJ,YAAY,IAAK;IAClC,MAAMK,WAAWL,WAAW;IAC5B,MAAMM,WAAWC,MAAM;IAEvB,IAAK,IAAIC,QAAQ,GAAGA,QAAQ,GAAGA,QAAS;QACtC,MAAMC,cAAc,IAAID;QACxB,MAAME,MAAM,AAACN,WAAWK,cAAe;QACvCH,QAAQ,CAACE,MAAM,GAAGE,QAAQ;IAC5B;IAEA,OAAO;QACLC,MAAMR,YAAY,IAAI,cAAc;QACpCG,UAAUA;QAQVM,aAAaP,aAAa;IAC5B;AACF;AAMO,SAASR,eACdgB,IAAe,EACfC,IAAyB;IAEzB,MAAMC,eAAe,IAAIR,MAAMM,KAAKd,MAAM;IAC1C,IAAIA,SAAS;IAEb,IAAK,IAAIS,QAAQ,GAAGA,QAAQK,KAAKd,MAAM,EAAES,QAAS;QAChD,IACE,AAACA,QAAQ,KAAKM,KAAKR,QAAQ,CAACE,MAAM,IAClC,wEAAwE;QACxE,0CAA0C;QACzCA,SAAS,KAAKM,KAAKF,WAAW,EAC/B;YACAG,YAAY,CAACP,MAAM,GAAGK,IAAI,CAACL,MAAM;YACjCT,SAASS,QAAQ;QACnB;IACF;IAEA,4CAA4C;IAC5CO,aAAahB,MAAM,GAAGA;IAEtB,OAAOgB;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/side-effect.d.ts b/e-commerce/node_modules/next/dist/shared/lib/side-effect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..561f956c21f082aa51b746af072a527076784d56 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/side-effect.d.ts @@ -0,0 +1,11 @@ +import type React from 'react'; +import { type JSX } from 'react'; +type State = JSX.Element[] | undefined; +export type SideEffectProps = { + reduceComponentsToState: (components: Array>) => State; + handleStateChange?: (state: State) => void; + headManager: any; + children: React.ReactNode; +}; +export default function SideEffect(props: SideEffectProps): null; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/side-effect.js b/e-commerce/node_modules/next/dist/shared/lib/side-effect.js new file mode 100644 index 0000000000000000000000000000000000000000..126a4f29c9fbb70bba5262a329af7ae3a1964b37 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/side-effect.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return SideEffect; + } +}); +const _react = require("react"); +const isServer = typeof window === 'undefined'; +const useClientOnlyLayoutEffect = isServer ? ()=>{} : _react.useLayoutEffect; +const useClientOnlyEffect = isServer ? ()=>{} : _react.useEffect; +function SideEffect(props) { + const { headManager, reduceComponentsToState } = props; + function emitChange() { + if (headManager && headManager.mountedInstances) { + const headElements = _react.Children.toArray(Array.from(headManager.mountedInstances).filter(Boolean)); + headManager.updateHead(reduceComponentsToState(headElements)); + } + } + if (isServer) { + headManager?.mountedInstances?.add(props.children); + emitChange(); + } + useClientOnlyLayoutEffect(()=>{ + headManager?.mountedInstances?.add(props.children); + return ()=>{ + headManager?.mountedInstances?.delete(props.children); + }; + }); + // We need to call `updateHead` method whenever the `SideEffect` is trigger in all + // life-cycles: mount, update, unmount. However, if there are multiple `SideEffect`s + // being rendered, we only trigger the method from the last one. + // This is ensured by keeping the last unflushed `updateHead` in the `_pendingUpdate` + // singleton in the layout effect pass, and actually trigger it in the effect pass. + useClientOnlyLayoutEffect(()=>{ + if (headManager) { + headManager._pendingUpdate = emitChange; + } + return ()=>{ + if (headManager) { + headManager._pendingUpdate = emitChange; + } + }; + }); + useClientOnlyEffect(()=>{ + if (headManager && headManager._pendingUpdate) { + headManager._pendingUpdate(); + headManager._pendingUpdate = null; + } + return ()=>{ + if (headManager && headManager._pendingUpdate) { + headManager._pendingUpdate(); + headManager._pendingUpdate = null; + } + }; + }); + return null; +} + +//# sourceMappingURL=side-effect.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/side-effect.js.map b/e-commerce/node_modules/next/dist/shared/lib/side-effect.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ec92278c06c22483c8c99c3b1902041839ab9fec --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/side-effect.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/side-effect.tsx"],"sourcesContent":["import type React from 'react'\nimport { Children, useEffect, useLayoutEffect, type JSX } from 'react'\n\ntype State = JSX.Element[] | undefined\n\nexport type SideEffectProps = {\n reduceComponentsToState: (components: Array>) => State\n handleStateChange?: (state: State) => void\n headManager: any\n children: React.ReactNode\n}\n\nconst isServer = typeof window === 'undefined'\nconst useClientOnlyLayoutEffect = isServer ? () => {} : useLayoutEffect\nconst useClientOnlyEffect = isServer ? () => {} : useEffect\n\nexport default function SideEffect(props: SideEffectProps) {\n const { headManager, reduceComponentsToState } = props\n\n function emitChange() {\n if (headManager && headManager.mountedInstances) {\n const headElements = Children.toArray(\n Array.from(headManager.mountedInstances as Set).filter(\n Boolean\n )\n ) as React.ReactElement[]\n headManager.updateHead(reduceComponentsToState(headElements))\n }\n }\n\n if (isServer) {\n headManager?.mountedInstances?.add(props.children)\n emitChange()\n }\n\n useClientOnlyLayoutEffect(() => {\n headManager?.mountedInstances?.add(props.children)\n return () => {\n headManager?.mountedInstances?.delete(props.children)\n }\n })\n\n // We need to call `updateHead` method whenever the `SideEffect` is trigger in all\n // life-cycles: mount, update, unmount. However, if there are multiple `SideEffect`s\n // being rendered, we only trigger the method from the last one.\n // This is ensured by keeping the last unflushed `updateHead` in the `_pendingUpdate`\n // singleton in the layout effect pass, and actually trigger it in the effect pass.\n useClientOnlyLayoutEffect(() => {\n if (headManager) {\n headManager._pendingUpdate = emitChange\n }\n return () => {\n if (headManager) {\n headManager._pendingUpdate = emitChange\n }\n }\n })\n\n useClientOnlyEffect(() => {\n if (headManager && headManager._pendingUpdate) {\n headManager._pendingUpdate()\n headManager._pendingUpdate = null\n }\n return () => {\n if (headManager && headManager._pendingUpdate) {\n headManager._pendingUpdate()\n headManager._pendingUpdate = null\n }\n }\n })\n\n return null\n}\n"],"names":["SideEffect","isServer","window","useClientOnlyLayoutEffect","useLayoutEffect","useClientOnlyEffect","useEffect","props","headManager","reduceComponentsToState","emitChange","mountedInstances","headElements","Children","toArray","Array","from","filter","Boolean","updateHead","add","children","delete","_pendingUpdate"],"mappings":";;;;+BAgBA;;;eAAwBA;;;uBAfuC;AAW/D,MAAMC,WAAW,OAAOC,WAAW;AACnC,MAAMC,4BAA4BF,WAAW,KAAO,IAAIG,sBAAe;AACvE,MAAMC,sBAAsBJ,WAAW,KAAO,IAAIK,gBAAS;AAE5C,SAASN,WAAWO,KAAsB;IACvD,MAAM,EAAEC,WAAW,EAAEC,uBAAuB,EAAE,GAAGF;IAEjD,SAASG;QACP,IAAIF,eAAeA,YAAYG,gBAAgB,EAAE;YAC/C,MAAMC,eAAeC,eAAQ,CAACC,OAAO,CACnCC,MAAMC,IAAI,CAACR,YAAYG,gBAAgB,EAA0BM,MAAM,CACrEC;YAGJV,YAAYW,UAAU,CAACV,wBAAwBG;QACjD;IACF;IAEA,IAAIX,UAAU;QACZO,aAAaG,kBAAkBS,IAAIb,MAAMc,QAAQ;QACjDX;IACF;IAEAP,0BAA0B;QACxBK,aAAaG,kBAAkBS,IAAIb,MAAMc,QAAQ;QACjD,OAAO;YACLb,aAAaG,kBAAkBW,OAAOf,MAAMc,QAAQ;QACtD;IACF;IAEA,kFAAkF;IAClF,oFAAoF;IACpF,gEAAgE;IAChE,qFAAqF;IACrF,mFAAmF;IACnFlB,0BAA0B;QACxB,IAAIK,aAAa;YACfA,YAAYe,cAAc,GAAGb;QAC/B;QACA,OAAO;YACL,IAAIF,aAAa;gBACfA,YAAYe,cAAc,GAAGb;YAC/B;QACF;IACF;IAEAL,oBAAoB;QAClB,IAAIG,eAAeA,YAAYe,cAAc,EAAE;YAC7Cf,YAAYe,cAAc;YAC1Bf,YAAYe,cAAc,GAAG;QAC/B;QACA,OAAO;YACL,IAAIf,eAAeA,YAAYe,cAAc,EAAE;gBAC7Cf,YAAYe,cAAc;gBAC1Bf,YAAYe,cAAc,GAAG;YAC/B;QACF;IACF;IAEA,OAAO;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/size-limit.d.ts b/e-commerce/node_modules/next/dist/shared/lib/size-limit.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d95b93e869abaae31382cbdd9c0c66b41a26f1f4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/size-limit.d.ts @@ -0,0 +1,6 @@ +import type { SizeLimit } from '../../types'; +export declare const DEFAULT_MAX_POSTPONED_STATE_SIZE: SizeLimit; +/** + * Parses the maxPostponedStateSize config value, using the default if not provided. + */ +export declare function parseMaxPostponedStateSize(size: SizeLimit | undefined): number | undefined; diff --git a/e-commerce/node_modules/next/dist/shared/lib/size-limit.js b/e-commerce/node_modules/next/dist/shared/lib/size-limit.js new file mode 100644 index 0000000000000000000000000000000000000000..c47220f5704f6a84cf4aa8537574b9c5364619e9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/size-limit.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DEFAULT_MAX_POSTPONED_STATE_SIZE: null, + parseMaxPostponedStateSize: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DEFAULT_MAX_POSTPONED_STATE_SIZE: function() { + return DEFAULT_MAX_POSTPONED_STATE_SIZE; + }, + parseMaxPostponedStateSize: function() { + return parseMaxPostponedStateSize; + } +}); +const DEFAULT_MAX_POSTPONED_STATE_SIZE = '100 MB'; +// 100MB in bytes. Not using the parseSizeLimit for performance as parseMaxPostponedStateSize is in the hot path for rendering. +const DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES = 104857600; +function parseSizeLimit(size) { + const bytes = require('next/dist/compiled/bytes').parse(size); + if (bytes === null || isNaN(bytes) || bytes < 1) { + return undefined; + } + return bytes; +} +function parseMaxPostponedStateSize(size) { + if (!size) { + return DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES; + } + return parseSizeLimit(size); +} + +//# sourceMappingURL=size-limit.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/size-limit.js.map b/e-commerce/node_modules/next/dist/shared/lib/size-limit.js.map new file mode 100644 index 0000000000000000000000000000000000000000..23b7277fea087cc726b36897cccab9e2726f6b77 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/size-limit.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/size-limit.ts"],"sourcesContent":["import type { SizeLimit } from '../../types'\n\nexport const DEFAULT_MAX_POSTPONED_STATE_SIZE: SizeLimit = '100 MB'\n\n// 100MB in bytes. Not using the parseSizeLimit for performance as parseMaxPostponedStateSize is in the hot path for rendering.\nconst DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES = 104_857_600\n\nfunction parseSizeLimit(size: SizeLimit): number | undefined {\n const bytes = (\n require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')\n ).parse(size)\n if (bytes === null || isNaN(bytes) || bytes < 1) {\n return undefined\n }\n return bytes\n}\n\n/**\n * Parses the maxPostponedStateSize config value, using the default if not provided.\n */\nexport function parseMaxPostponedStateSize(\n size: SizeLimit | undefined\n): number | undefined {\n if (!size) {\n return DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES\n }\n return parseSizeLimit(size)\n}\n"],"names":["DEFAULT_MAX_POSTPONED_STATE_SIZE","parseMaxPostponedStateSize","DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES","parseSizeLimit","size","bytes","require","parse","isNaN","undefined"],"mappings":";;;;;;;;;;;;;;;IAEaA,gCAAgC;eAAhCA;;IAkBGC,0BAA0B;eAA1BA;;;AAlBT,MAAMD,mCAA8C;AAE3D,+HAA+H;AAC/H,MAAME,yCAAyC;AAE/C,SAASC,eAAeC,IAAe;IACrC,MAAMC,QAAQ,AACZC,QAAQ,4BACRC,KAAK,CAACH;IACR,IAAIC,UAAU,QAAQG,MAAMH,UAAUA,QAAQ,GAAG;QAC/C,OAAOI;IACT;IACA,OAAOJ;AACT;AAKO,SAASJ,2BACdG,IAA2B;IAE3B,IAAI,CAACA,MAAM;QACT,OAAOF;IACT;IACA,OAAOC,eAAeC;AACxB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.d.ts b/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57be2222c272af3ae470dd3bb8b99ee264193819 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.d.ts @@ -0,0 +1 @@ +export { default } from 'styled-jsx/style' diff --git a/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.js b/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.js new file mode 100644 index 0000000000000000000000000000000000000000..adb6b9b315761d45df0bb23447d2c7f5683559c1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('styled-jsx/style'); + +//# sourceMappingURL=styled-jsx.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.js.map b/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.js.map new file mode 100644 index 0000000000000000000000000000000000000000..25c5a9fff41615538b7757e2ed954fc297ab75e5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/styled-jsx.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/styled-jsx.js"],"sourcesContent":["module.exports = require('styled-jsx/style')\n"],"names":["module","exports","require"],"mappings":";AAAAA,OAAOC,OAAO,GAAGC,QAAQ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.d.ts b/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c383dccb27c91dd63a671cfbdb04af5a4f59226e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.d.ts @@ -0,0 +1,20 @@ +import type { Project } from '../../../build/swc/types'; +import { type Span } from '../../../trace'; +export declare function msToNs(ms: number): bigint; +/** + * Subscribes to compilation events for `project` and prints them using the + * `Log` library. + * + * When `parentSpan` is provided, `TraceEvent` compilation events are recorded + * as trace spans in the `.next/trace` file. + * + * Returns a promise that resolves when the subscription ends. Abort the + * `signal` to close the underlying async iterator and settle the promise + * promptly. The iterator also closes automatically when the Rust side + * drops the subscription (e.g. after project shutdown). + */ +export declare function backgroundLogCompilationEvents(project: Project, { eventTypes, signal, parentSpan, }?: { + eventTypes?: string[]; + signal?: AbortSignal; + parentSpan?: Span; +}): Promise; diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.js b/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.js new file mode 100644 index 0000000000000000000000000000000000000000..6bf6d9f26f6cfda278f4d25e448f983982dfc394 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.js @@ -0,0 +1,83 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + backgroundLogCompilationEvents: null, + msToNs: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + backgroundLogCompilationEvents: function() { + return backgroundLogCompilationEvents; + }, + msToNs: function() { + return msToNs; + } +}); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _log = /*#__PURE__*/ _interop_require_wildcard._(require("../../../build/output/log")); +const _trace = require("../../../trace"); +const _trace1 = require("../../../lib/memory/trace"); +const MILLISECONDS_IN_NANOSECOND = BigInt(1000000); +function msToNs(ms) { + return BigInt(Math.floor(ms)) * MILLISECONDS_IN_NANOSECOND; +} +function backgroundLogCompilationEvents(project, { eventTypes, signal, parentSpan } = {}) { + const iterator = project.compilationEventsSubscribe(eventTypes); + // If there is no signal assume there will be no clean shutdown, + // to ensure trace spans aren't lost just flush after each one. + const flushEachTraceEvent = signal === undefined; + // Close the iterator as soon as the signal fires so the for-await loop + // exits without waiting for the next compilation event. + signal?.addEventListener('abort', ()=>iterator.return?.(undefined), { + once: true + }); + const promise = async function() { + for await (const event of iterator){ + // Record TraceEvent compilation events as trace spans in .next/trace. + if (parentSpan && event.typeName === 'TraceEvent' && event.eventJson) { + try { + const data = JSON.parse(event.eventJson); + parentSpan.manualTraceChild(data.name, msToNs(data.startTimeMs), msToNs(data.endTimeMs), Object.fromEntries(data.attributes ?? [])); + (0, _trace1.traceMemoryUsage)(data.name, parentSpan); + if (flushEachTraceEvent) { + (0, _trace.flushAllTraces)(); + } + } catch {} + continue; // don't log these events, they just go to the trace file + } + switch(event.severity){ + case 'EVENT': + _log.event(event.message); + break; + case 'TRACE': + _log.trace(event.message); + break; + case 'INFO': + _log.info(event.message); + break; + case 'WARNING': + _log.warn(event.message); + break; + case 'ERROR': + _log.error(event.message); + break; + case 'FATAL': + _log.error(event.message); + break; + default: + break; + } + } + }(); + // Prevent unhandled rejection if the subscription errors after the project shuts down. + return promise.catch(()=>{}); +} + +//# sourceMappingURL=compilation-events.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.js.map b/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.js.map new file mode 100644 index 0000000000000000000000000000000000000000..be94a4f068f5e554c592346e09147ade1fcd0002 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/compilation-events.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/turbopack/compilation-events.ts"],"sourcesContent":["import type { Project } from '../../../build/swc/types'\nimport * as Log from '../../../build/output/log'\nimport { flushAllTraces, type Span } from '../../../trace'\nimport { traceMemoryUsage } from '../../../lib/memory/trace'\n\nconst MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000)\nexport function msToNs(ms: number): bigint {\n return BigInt(Math.floor(ms)) * MILLISECONDS_IN_NANOSECOND\n}\n\n/**\n * Subscribes to compilation events for `project` and prints them using the\n * `Log` library.\n *\n * When `parentSpan` is provided, `TraceEvent` compilation events are recorded\n * as trace spans in the `.next/trace` file.\n *\n * Returns a promise that resolves when the subscription ends. Abort the\n * `signal` to close the underlying async iterator and settle the promise\n * promptly. The iterator also closes automatically when the Rust side\n * drops the subscription (e.g. after project shutdown).\n */\nexport function backgroundLogCompilationEvents(\n project: Project,\n {\n eventTypes,\n signal,\n parentSpan,\n }: { eventTypes?: string[]; signal?: AbortSignal; parentSpan?: Span } = {}\n): Promise {\n const iterator = project.compilationEventsSubscribe(eventTypes)\n\n // If there is no signal assume there will be no clean shutdown,\n // to ensure trace spans aren't lost just flush after each one.\n const flushEachTraceEvent = signal === undefined\n\n // Close the iterator as soon as the signal fires so the for-await loop\n // exits without waiting for the next compilation event.\n signal?.addEventListener('abort', () => iterator.return?.(undefined as any), {\n once: true,\n })\n\n const promise = (async function () {\n for await (const event of iterator) {\n // Record TraceEvent compilation events as trace spans in .next/trace.\n if (parentSpan && event.typeName === 'TraceEvent' && event.eventJson) {\n try {\n const data = JSON.parse(event.eventJson)\n parentSpan.manualTraceChild(\n data.name,\n msToNs(data.startTimeMs),\n msToNs(data.endTimeMs),\n Object.fromEntries(data.attributes ?? [])\n )\n traceMemoryUsage(data.name, parentSpan)\n if (flushEachTraceEvent) {\n flushAllTraces()\n }\n } catch {}\n continue // don't log these events, they just go to the trace file\n }\n\n switch (event.severity) {\n case 'EVENT':\n Log.event(event.message)\n break\n case 'TRACE':\n Log.trace(event.message)\n break\n case 'INFO':\n Log.info(event.message)\n break\n case 'WARNING':\n Log.warn(event.message)\n break\n case 'ERROR':\n Log.error(event.message)\n break\n case 'FATAL':\n Log.error(event.message)\n break\n default:\n break\n }\n }\n })()\n // Prevent unhandled rejection if the subscription errors after the project shuts down.\n return promise.catch(() => {})\n}\n"],"names":["backgroundLogCompilationEvents","msToNs","MILLISECONDS_IN_NANOSECOND","BigInt","ms","Math","floor","project","eventTypes","signal","parentSpan","iterator","compilationEventsSubscribe","flushEachTraceEvent","undefined","addEventListener","return","once","promise","event","typeName","eventJson","data","JSON","parse","manualTraceChild","name","startTimeMs","endTimeMs","Object","fromEntries","attributes","traceMemoryUsage","flushAllTraces","severity","Log","message","trace","info","warn","error","catch"],"mappings":";;;;;;;;;;;;;;;IAsBgBA,8BAA8B;eAA9BA;;IAhBAC,MAAM;eAANA;;;;+DALK;uBACqB;wBACT;AAEjC,MAAMC,6BAA6BC,OAAO;AACnC,SAASF,OAAOG,EAAU;IAC/B,OAAOD,OAAOE,KAAKC,KAAK,CAACF,OAAOF;AAClC;AAcO,SAASF,+BACdO,OAAgB,EAChB,EACEC,UAAU,EACVC,MAAM,EACNC,UAAU,EACyD,GAAG,CAAC,CAAC;IAE1E,MAAMC,WAAWJ,QAAQK,0BAA0B,CAACJ;IAEpD,gEAAgE;IAChE,+DAA+D;IAC/D,MAAMK,sBAAsBJ,WAAWK;IAEvC,uEAAuE;IACvE,wDAAwD;IACxDL,QAAQM,iBAAiB,SAAS,IAAMJ,SAASK,MAAM,GAAGF,YAAmB;QAC3EG,MAAM;IACR;IAEA,MAAMC,UAAU,AAAC;QACf,WAAW,MAAMC,SAASR,SAAU;YAClC,sEAAsE;YACtE,IAAID,cAAcS,MAAMC,QAAQ,KAAK,gBAAgBD,MAAME,SAAS,EAAE;gBACpE,IAAI;oBACF,MAAMC,OAAOC,KAAKC,KAAK,CAACL,MAAME,SAAS;oBACvCX,WAAWe,gBAAgB,CACzBH,KAAKI,IAAI,EACTzB,OAAOqB,KAAKK,WAAW,GACvB1B,OAAOqB,KAAKM,SAAS,GACrBC,OAAOC,WAAW,CAACR,KAAKS,UAAU,IAAI,EAAE;oBAE1CC,IAAAA,wBAAgB,EAACV,KAAKI,IAAI,EAAEhB;oBAC5B,IAAIG,qBAAqB;wBACvBoB,IAAAA,qBAAc;oBAChB;gBACF,EAAE,OAAM,CAAC;gBACT,UAAS,yDAAyD;YACpE;YAEA,OAAQd,MAAMe,QAAQ;gBACpB,KAAK;oBACHC,KAAIhB,KAAK,CAACA,MAAMiB,OAAO;oBACvB;gBACF,KAAK;oBACHD,KAAIE,KAAK,CAAClB,MAAMiB,OAAO;oBACvB;gBACF,KAAK;oBACHD,KAAIG,IAAI,CAACnB,MAAMiB,OAAO;oBACtB;gBACF,KAAK;oBACHD,KAAII,IAAI,CAACpB,MAAMiB,OAAO;oBACtB;gBACF,KAAK;oBACHD,KAAIK,KAAK,CAACrB,MAAMiB,OAAO;oBACvB;gBACF,KAAK;oBACHD,KAAIK,KAAK,CAACrB,MAAMiB,OAAO;oBACvB;gBACF;oBACE;YACJ;QACF;IACF;IACA,uFAAuF;IACvF,OAAOlB,QAAQuB,KAAK,CAAC,KAAO;AAC9B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.d.ts b/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d401cacdc5b798ff5f434b55e7fb8825002c8898 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.d.ts @@ -0,0 +1,24 @@ +/** + * Fires a callback after a delay unless it's cancelled or flushed first. + * + * `schedule()` replaces any still-pending emit. + */ +export declare class DeferredEmit { + #private; + /** + * Arm `fn` to run after `delayMs`, replacing any still-pending emit. + * + * @param delayMs The delay in milliseconds before the callback is fired. + * @param fn The callback function to be executed after the delay. + */ + schedule(delayMs: number, scheduledFn: () => void): void; + /** + * If an emit is pending, run it now instead of waiting for the delay. + */ + flush(): void; + /** + * Cancel a pending emit without running it. + */ + cancel(): void; + get isPending(): boolean; +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.js b/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.js new file mode 100644 index 0000000000000000000000000000000000000000..a32b94040ab7a6c598dc233bb625376a8a126dfc --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.js @@ -0,0 +1,60 @@ +/** + * Fires a callback after a delay unless it's cancelled or flushed first. + * + * `schedule()` replaces any still-pending emit. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "DeferredEmit", { + enumerable: true, + get: function() { + return DeferredEmit; + } +}); +class DeferredEmit { + #timer; + #fn; + /** + * Arm `fn` to run after `delayMs`, replacing any still-pending emit. + * + * @param delayMs The delay in milliseconds before the callback is fired. + * @param fn The callback function to be executed after the delay. + */ schedule(delayMs, scheduledFn) { + this.cancel(); + this.#fn = scheduledFn; + this.#timer = setTimeout(()=>{ + this.#timer = undefined; + const fn = this.#fn; + this.#fn = undefined; + fn?.(); + }, delayMs); + } + /** + * If an emit is pending, run it now instead of waiting for the delay. + */ flush() { + if (this.#timer === undefined) { + return; + } + clearTimeout(this.#timer); + this.#timer = undefined; + const fn = this.#fn; + this.#fn = undefined; + fn?.(); + } + /** + * Cancel a pending emit without running it. + */ cancel() { + if (this.#timer === undefined) { + return; + } + clearTimeout(this.#timer); + this.#timer = undefined; + this.#fn = undefined; + } + get isPending() { + return this.#timer !== undefined; + } +} + +//# sourceMappingURL=deferred-emit.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.js.map b/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.js.map new file mode 100644 index 0000000000000000000000000000000000000000..276602cf1553ca7ce3b34f3fabf58827f682960a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/deferred-emit.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/turbopack/deferred-emit.ts"],"sourcesContent":["/**\n * Fires a callback after a delay unless it's cancelled or flushed first.\n *\n * `schedule()` replaces any still-pending emit.\n */\nexport class DeferredEmit {\n #timer: ReturnType | undefined\n #fn: (() => void) | undefined\n\n /**\n * Arm `fn` to run after `delayMs`, replacing any still-pending emit.\n *\n * @param delayMs The delay in milliseconds before the callback is fired.\n * @param fn The callback function to be executed after the delay.\n */\n schedule(delayMs: number, scheduledFn: () => void): void {\n this.cancel()\n this.#fn = scheduledFn\n this.#timer = setTimeout(() => {\n this.#timer = undefined\n const fn = this.#fn\n this.#fn = undefined\n fn?.()\n }, delayMs)\n }\n\n /**\n * If an emit is pending, run it now instead of waiting for the delay.\n */\n flush(): void {\n if (this.#timer === undefined) {\n return\n }\n clearTimeout(this.#timer)\n this.#timer = undefined\n const fn = this.#fn\n this.#fn = undefined\n fn?.()\n }\n\n /**\n * Cancel a pending emit without running it.\n */\n cancel(): void {\n if (this.#timer === undefined) {\n return\n }\n clearTimeout(this.#timer)\n this.#timer = undefined\n this.#fn = undefined\n }\n\n get isPending(): boolean {\n return this.#timer !== undefined\n }\n}\n"],"names":["DeferredEmit","schedule","delayMs","scheduledFn","cancel","setTimeout","undefined","fn","flush","clearTimeout","isPending"],"mappings":"AAAA;;;;CAIC;;;;+BACYA;;;eAAAA;;;AAAN,MAAMA;IACX,CAAA,KAAM,CAA2C;IACjD,CAAA,EAAG,CAA0B;IAE7B;;;;;GAKC,GACDC,SAASC,OAAe,EAAEC,WAAuB,EAAQ;QACvD,IAAI,CAACC,MAAM;QACX,IAAI,CAAC,CAAA,EAAG,GAAGD;QACX,IAAI,CAAC,CAAA,KAAM,GAAGE,WAAW;YACvB,IAAI,CAAC,CAAA,KAAM,GAAGC;YACd,MAAMC,KAAK,IAAI,CAAC,CAAA,EAAG;YACnB,IAAI,CAAC,CAAA,EAAG,GAAGD;YACXC;QACF,GAAGL;IACL;IAEA;;GAEC,GACDM,QAAc;QACZ,IAAI,IAAI,CAAC,CAAA,KAAM,KAAKF,WAAW;YAC7B;QACF;QACAG,aAAa,IAAI,CAAC,CAAA,KAAM;QACxB,IAAI,CAAC,CAAA,KAAM,GAAGH;QACd,MAAMC,KAAK,IAAI,CAAC,CAAA,EAAG;QACnB,IAAI,CAAC,CAAA,EAAG,GAAGD;QACXC;IACF;IAEA;;GAEC,GACDH,SAAe;QACb,IAAI,IAAI,CAAC,CAAA,KAAM,KAAKE,WAAW;YAC7B;QACF;QACAG,aAAa,IAAI,CAAC,CAAA,KAAM;QACxB,IAAI,CAAC,CAAA,KAAM,GAAGH;QACd,IAAI,CAAC,CAAA,EAAG,GAAGA;IACb;IAEA,IAAII,YAAqB;QACvB,OAAO,IAAI,CAAC,CAAA,KAAM,KAAKJ;IACzB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.d.ts b/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5eb1cc31d5debac9efac58a8401f1b5b3c0c7dd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.d.ts @@ -0,0 +1,21 @@ +/** + * `app` -> app dir + * `pages` -> pages dir + * `root` -> middleware / instrumentation + * `assets` -> assets + */ +export type EntryKeyType = 'app' | 'pages' | 'root' | 'assets'; +export type EntryKeySide = 'client' | 'server'; +export type EntryKey = `{"type":"${EntryKeyType}","side":"${EntryKeyType}","page":"${string}"}`; +/** + * Get a key that's unique across all entrypoints. + */ +export declare function getEntryKey(type: EntryKeyType, side: EntryKeySide, page: string): EntryKey; +/** + * Split an `EntryKey` up into its components. + */ +export declare function splitEntryKey(key: EntryKey): { + type: EntryKeyType; + side: EntryKeySide; + page: string; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.js b/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.js new file mode 100644 index 0000000000000000000000000000000000000000..7e8d0d418c1d51ac01c9a451a5b2235c2dccc617 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.js @@ -0,0 +1,39 @@ +/** + * `app` -> app dir + * `pages` -> pages dir + * `root` -> middleware / instrumentation + * `assets` -> assets + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getEntryKey: null, + splitEntryKey: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getEntryKey: function() { + return getEntryKey; + }, + splitEntryKey: function() { + return splitEntryKey; + } +}); +function getEntryKey(type, side, page) { + return JSON.stringify({ + type, + side, + page + }); +} +function splitEntryKey(key) { + return JSON.parse(key); +} + +//# sourceMappingURL=entry-key.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.js.map b/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.js.map new file mode 100644 index 0000000000000000000000000000000000000000..23c94a9351ba272cb4a4d6031aecc8af3304df97 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/entry-key.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/turbopack/entry-key.ts"],"sourcesContent":["/**\n * `app` -> app dir\n * `pages` -> pages dir\n * `root` -> middleware / instrumentation\n * `assets` -> assets\n */\nexport type EntryKeyType = 'app' | 'pages' | 'root' | 'assets'\nexport type EntryKeySide = 'client' | 'server'\n\n// custom type to make sure you can't accidentally use a \"generic\" string\nexport type EntryKey =\n `{\"type\":\"${EntryKeyType}\",\"side\":\"${EntryKeyType}\",\"page\":\"${string}\"}`\n\n/**\n * Get a key that's unique across all entrypoints.\n */\nexport function getEntryKey(\n type: EntryKeyType,\n side: EntryKeySide,\n page: string\n): EntryKey {\n return JSON.stringify({ type, side, page }) as EntryKey\n}\n\n/**\n * Split an `EntryKey` up into its components.\n */\nexport function splitEntryKey(key: EntryKey): {\n type: EntryKeyType\n side: EntryKeySide\n page: string\n} {\n return JSON.parse(key)\n}\n"],"names":["getEntryKey","splitEntryKey","type","side","page","JSON","stringify","key","parse"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;;;;;IAWeA,WAAW;eAAXA;;IAWAC,aAAa;eAAbA;;;AAXT,SAASD,YACdE,IAAkB,EAClBC,IAAkB,EAClBC,IAAY;IAEZ,OAAOC,KAAKC,SAAS,CAAC;QAAEJ;QAAMC;QAAMC;IAAK;AAC3C;AAKO,SAASH,cAAcM,GAAa;IAKzC,OAAOF,KAAKG,KAAK,CAACD;AACpB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c5132226f9b3f1677c3d7d7f91c73598073858b7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.d.ts @@ -0,0 +1,18 @@ +import type { TurbopackInternalErrorOpts } from '../../../build/swc/generated-native'; +/** + * An error caused by a bug in Turbopack, and not the user's code (e.g. a Rust panic). These should + * be written to a log file and details should not be shown to the user. + * + * These are constructed in Turbopack by calling `throwTurbopackInternalError`. + */ +export declare class TurbopackInternalError extends Error { + name: string; + location: string | undefined; + constructor({ message, anonymizedLocation }: TurbopackInternalErrorOpts); +} +/** + * A helper used by the napi Rust entrypoints to construct and throw a `TurbopackInternalError`. + * + * When called, this will emit a telemetry event. + */ +export declare function throwTurbopackInternalError(conversionError: Error | null, opts: TurbopackInternalErrorOpts): never; diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.js b/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.js new file mode 100644 index 0000000000000000000000000000000000000000..ea3c218a78301ef13888ab8999359cee9ac64a75 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + TurbopackInternalError: null, + throwTurbopackInternalError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + TurbopackInternalError: function() { + return TurbopackInternalError; + }, + throwTurbopackInternalError: function() { + return throwTurbopackInternalError; + } +}); +const _events = require("../../../telemetry/events"); +const _shared = require("../../../trace/shared"); +class TurbopackInternalError extends Error { + constructor({ message, anonymizedLocation }){ + super(message), this.name = 'TurbopackInternalError'; + this.location = anonymizedLocation; + } +} +function throwTurbopackInternalError(conversionError, opts) { + if (conversionError != null) { + // Somehow napi failed to convert `opts` to a JS object??? Just give up and throw that instead. + throw new Error('NAPI type conversion error in throwTurbopackInternalError', { + cause: conversionError + }); + } + const err = new TurbopackInternalError(opts); + const telemetry = _shared.traceGlobals.get('telemetry'); + if (telemetry) { + telemetry.record((0, _events.eventErrorThrown)(err, opts.anonymizedLocation)); + } else { + console.error('Expected `telemetry` to be set in globals'); + } + throw err; +} + +//# sourceMappingURL=internal-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..aa51fc5f34ceae0f28b1e0e7be962b9531489553 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/internal-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/turbopack/internal-error.ts"],"sourcesContent":["import type { TurbopackInternalErrorOpts } from '../../../build/swc/generated-native'\nimport { eventErrorThrown } from '../../../telemetry/events'\nimport { traceGlobals } from '../../../trace/shared'\n\n/**\n * An error caused by a bug in Turbopack, and not the user's code (e.g. a Rust panic). These should\n * be written to a log file and details should not be shown to the user.\n *\n * These are constructed in Turbopack by calling `throwTurbopackInternalError`.\n */\nexport class TurbopackInternalError extends Error {\n name = 'TurbopackInternalError'\n location: string | undefined\n\n constructor({ message, anonymizedLocation }: TurbopackInternalErrorOpts) {\n super(message)\n this.location = anonymizedLocation\n }\n}\n\n/**\n * A helper used by the napi Rust entrypoints to construct and throw a `TurbopackInternalError`.\n *\n * When called, this will emit a telemetry event.\n */\nexport function throwTurbopackInternalError(\n conversionError: Error | null,\n opts: TurbopackInternalErrorOpts\n): never {\n if (conversionError != null) {\n // Somehow napi failed to convert `opts` to a JS object??? Just give up and throw that instead.\n throw new Error(\n 'NAPI type conversion error in throwTurbopackInternalError',\n {\n cause: conversionError,\n }\n )\n }\n const err = new TurbopackInternalError(opts)\n const telemetry = traceGlobals.get('telemetry')\n if (telemetry) {\n telemetry.record(eventErrorThrown(err, opts.anonymizedLocation))\n } else {\n console.error('Expected `telemetry` to be set in globals')\n }\n throw err\n}\n"],"names":["TurbopackInternalError","throwTurbopackInternalError","Error","constructor","message","anonymizedLocation","name","location","conversionError","opts","cause","err","telemetry","traceGlobals","get","record","eventErrorThrown","console","error"],"mappings":";;;;;;;;;;;;;;;IAUaA,sBAAsB;eAAtBA;;IAeGC,2BAA2B;eAA3BA;;;wBAxBiB;wBACJ;AAQtB,MAAMD,+BAA+BE;IAI1CC,YAAY,EAAEC,OAAO,EAAEC,kBAAkB,EAA8B,CAAE;QACvE,KAAK,CAACD,eAJRE,OAAO;QAKL,IAAI,CAACC,QAAQ,GAAGF;IAClB;AACF;AAOO,SAASJ,4BACdO,eAA6B,EAC7BC,IAAgC;IAEhC,IAAID,mBAAmB,MAAM;QAC3B,+FAA+F;QAC/F,MAAM,IAAIN,MACR,6DACA;YACEQ,OAAOF;QACT;IAEJ;IACA,MAAMG,MAAM,IAAIX,uBAAuBS;IACvC,MAAMG,YAAYC,oBAAY,CAACC,GAAG,CAAC;IACnC,IAAIF,WAAW;QACbA,UAAUG,MAAM,CAACC,IAAAA,wBAAgB,EAACL,KAAKF,KAAKJ,kBAAkB;IAChE,OAAO;QACLY,QAAQC,KAAK,CAAC;IAChB;IACA,MAAMP;AACR","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.d.ts b/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a980282dd4a387d244bfcb170117034d36dc4e4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.d.ts @@ -0,0 +1,72 @@ +import type { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-plugin'; +import type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'; +import { type EntryKey } from './entry-key'; +import type { CustomRoutes } from '../../../lib/load-custom-routes'; +import type { Entrypoints } from '../../../build/swc/types'; +interface InstrumentationDefinition { + files: string[]; + name: 'instrumentation'; +} +type TurbopackMiddlewareManifest = MiddlewareManifest & { + instrumentation?: InstrumentationDefinition; +}; +export declare class TurbopackManifestLoader { + private actionManifests; + private appPathsManifests; + private buildManifests; + private clientBuildManifests; + private fontManifests; + private middlewareManifests; + private pagesManifests; + private sriManifests; + private encryptionKey; + private cachedInterceptionRewrites; + private pendingCacheDeletes; + private readonly distDir; + private readonly buildId; + private readonly dev; + private readonly sriEnabled; + constructor({ distDir, buildId, encryptionKey, dev, sriEnabled, }: { + buildId: string; + distDir: string; + encryptionKey: string; + dev: boolean; + sriEnabled: boolean; + }); + delete(key: EntryKey): void; + loadActionManifest(pageName: string): void; + private mergeActionManifests; + private writeActionManifest; + loadAppPathsManifest(pageName: string): void; + private writeAppPathsManifest; + private writeSriManifest; + loadBuildManifest(pageName: string, type?: 'app' | 'pages'): void; + loadClientBuildManifest(pageName: string, type?: 'app' | 'pages'): void; + loadSriManifest(pageName: string, type?: 'app' | 'pages'): void; + private mergeBuildManifests; + private mergeClientBuildManifests; + private writeInterceptionRouteRewriteManifest; + private writeBuildManifest; + private writeClientBuildManifest; + loadFontManifest(pageName: string, type?: 'app' | 'pages'): void; + private mergeFontManifests; + private writeNextFontManifest; + /** + * @returns If the manifest was written or not + */ + loadMiddlewareManifest(pageName: string, type: 'pages' | 'app' | 'middleware' | 'instrumentation'): boolean; + getMiddlewareManifest(key: EntryKey): TurbopackMiddlewareManifest | undefined; + deleteMiddlewareManifest(key: EntryKey): void; + private mergeMiddlewareManifests; + private writeMiddlewareManifest; + loadPagesManifest(pageName: string): void; + private mergePagesManifests; + private mergeSriManifests; + private writePagesManifest; + writeManifests({ devRewrites, productionRewrites, entrypoints, }: { + devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined; + productionRewrites: CustomRoutes['rewrites'] | undefined; + entrypoints: Entrypoints; + }): void; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.js b/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.js new file mode 100644 index 0000000000000000000000000000000000000000..5f2bb4edd2b94687e6208edf1a0e2fddfb607551 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.js @@ -0,0 +1,524 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "TurbopackManifestLoader", { + enumerable: true, + get: function() { + return TurbopackManifestLoader; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _constants = require("../constants"); +const _path = require("path"); +const _fs = require("fs"); +const _requirecache = require("../../../server/dev/require-cache"); +const _writeatomic = require("../../../lib/fs/write-atomic"); +const _getassetpathfromroute = /*#__PURE__*/ _interop_require_default._(require("../router/utils/get-asset-path-from-route")); +const _entrykey = require("./entry-key"); +const _utils = require("../router/utils"); +const _turbopackutils = require("../../../server/dev/turbopack-utils"); +const _trytoparsepath = require("../../../lib/try-to-parse-path"); +const _routematchutils = require("../router/utils/route-match-utils"); +const _buildmanifestpluginutils = require("../../../build/webpack/plugins/build-manifest-plugin-utils"); +const getManifestPath = (page, distDir, name, type, firstCall)=>{ + let manifestPath = _path.posix.join(distDir, `server`, type, type === 'middleware' || type === 'instrumentation' ? '' : type === 'app' ? page : (0, _getassetpathfromroute.default)(page), name); + if (firstCall) { + const isSitemapRoute = /[\\/]sitemap(.xml)?\/route$/.test(page); + // Check the ambiguity of /sitemap and /sitemap.xml + if (isSitemapRoute && !(0, _fs.existsSync)(manifestPath)) { + manifestPath = getManifestPath(page.replace(/\/sitemap\/route$/, '/sitemap.xml/route'), distDir, name, type, false); + } + // existsSync is faster than using the async version + if (!(0, _fs.existsSync)(manifestPath) && page.endsWith('/route')) { + // TODO: Improve implementation of metadata routes, currently it requires this extra check for the variants of the files that can be written. + let basePage = (0, _turbopackutils.removeRouteSuffix)(page); + // For sitemap.xml routes with generateSitemaps, the manifest is at + // /sitemap/[__metadata_id__]/route (without .xml), because the route + // handler serves at /sitemap/[id] not /sitemap.xml/[id] + if (basePage.endsWith('/sitemap.xml')) { + basePage = basePage.slice(0, -'.xml'.length); + } + let metadataPage = (0, _turbopackutils.addRouteSuffix)((0, _turbopackutils.addMetadataIdToRoute)(basePage)); + manifestPath = getManifestPath(metadataPage, distDir, name, type, false); + } + } + return manifestPath; +}; +function readPartialManifestContent(distDir, name, pageName, type = 'pages') { + const page = pageName; + const manifestPath = getManifestPath(page, distDir, name, type, true); + return (0, _fs.readFileSync)(_path.posix.join(manifestPath), 'utf-8'); +} +/// Helper class that stores a map of manifests and tracks if they have changed +/// since the last time they were written to disk. This is used to avoid +/// unnecessary writes to disk. +class ManifestsMap { + set(key, value) { + if (this.rawMap.get(key) === value) return; + this.changed = true; + this.rawMap.set(key, value); + this.map.set(key, JSON.parse(value)); + } + delete(key) { + if (this.map.has(key)) { + this.changed = true; + this.rawMap.delete(key); + this.map.delete(key); + } + } + get(key) { + return this.map.get(key); + } + takeChanged(extraInvalidationKey) { + let changed = this.changed; + if (extraInvalidationKey !== undefined) { + const stringified = JSON.stringify(extraInvalidationKey); + if (this.extraInvalidationKey !== stringified) { + this.extraInvalidationKey = stringified; + changed = true; + } + } + this.changed = false; + return changed; + } + values() { + return this.map.values(); + } + entries() { + return this.map.entries(); + } + constructor(){ + this.rawMap = new Map(); + this.map = new Map(); + this.extraInvalidationKey = undefined; + this.changed = true; + } +} +class TurbopackManifestLoader { + constructor({ distDir, buildId, encryptionKey, dev, sriEnabled }){ + this.actionManifests = new ManifestsMap(); + this.appPathsManifests = new ManifestsMap(); + this.buildManifests = new ManifestsMap(); + this.clientBuildManifests = new ManifestsMap(); + this.fontManifests = new ManifestsMap(); + this.middlewareManifests = new ManifestsMap(); + this.pagesManifests = new ManifestsMap(); + this.sriManifests = new ManifestsMap(); + /// interceptionRewrites that have been written to disk + /// This is used to avoid unnecessary writes if the rewrites haven't changed + this.cachedInterceptionRewrites = undefined; + this.pendingCacheDeletes = []; + this.distDir = distDir; + this.buildId = buildId; + this.encryptionKey = encryptionKey; + this.dev = dev; + this.sriEnabled = sriEnabled; + } + delete(key) { + this.actionManifests.delete(key); + this.appPathsManifests.delete(key); + this.buildManifests.delete(key); + this.clientBuildManifests.delete(key); + this.fontManifests.delete(key); + this.middlewareManifests.delete(key); + this.pagesManifests.delete(key); + } + loadActionManifest(pageName) { + this.actionManifests.set((0, _entrykey.getEntryKey)('app', 'server', pageName), readPartialManifestContent(this.distDir, `${_constants.SERVER_REFERENCE_MANIFEST}.json`, pageName, 'app')); + } + mergeActionManifests(manifests) { + const manifest = { + node: {}, + edge: {}, + encryptionKey: this.encryptionKey + }; + function mergeActionIds(actionEntries, other) { + for(const key in other){ + const action = actionEntries[key] ??= { + workers: {} + }; + action.filename = other[key].filename; + action.exportedName = other[key].exportedName; + Object.assign(action.workers, other[key].workers); + } + } + for (const m of manifests){ + mergeActionIds(manifest.node, m.node); + mergeActionIds(manifest.edge, m.edge); + } + for(const key in manifest.node){ + const entry = manifest.node[key]; + entry.workers = sortObjectByKey(entry.workers); + } + for(const key in manifest.edge){ + const entry = manifest.edge[key]; + entry.workers = sortObjectByKey(entry.workers); + } + return manifest; + } + writeActionManifest() { + if (!this.actionManifests.takeChanged()) { + return; + } + const actionManifest = this.mergeActionManifests(this.actionManifests.values()); + const actionManifestJsonPath = (0, _path.join)(this.distDir, 'server', `${_constants.SERVER_REFERENCE_MANIFEST}.json`); + const actionManifestJsPath = (0, _path.join)(this.distDir, 'server', `${_constants.SERVER_REFERENCE_MANIFEST}.js`); + const json = JSON.stringify(actionManifest, null, 2); + this.pendingCacheDeletes.push(actionManifestJsonPath); + this.pendingCacheDeletes.push(actionManifestJsPath); + (0, _writeatomic.writeFileAtomic)(actionManifestJsonPath, json); + (0, _writeatomic.writeFileAtomic)(actionManifestJsPath, `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`); + } + loadAppPathsManifest(pageName) { + this.appPathsManifests.set((0, _entrykey.getEntryKey)('app', 'server', pageName), readPartialManifestContent(this.distDir, _constants.APP_PATHS_MANIFEST, pageName, 'app')); + } + writeAppPathsManifest() { + if (!this.appPathsManifests.takeChanged()) { + return; + } + const appPathsManifest = this.mergePagesManifests(this.appPathsManifests.values()); + const appPathsManifestPath = (0, _path.join)(this.distDir, 'server', _constants.APP_PATHS_MANIFEST); + this.pendingCacheDeletes.push(appPathsManifestPath); + (0, _writeatomic.writeFileAtomic)(appPathsManifestPath, JSON.stringify(appPathsManifest, null, 2)); + } + writeSriManifest() { + if (!this.sriEnabled || !this.sriManifests.takeChanged()) { + return; + } + const sriManifest = this.mergeSriManifests(this.sriManifests.values()); + const pathJson = (0, _path.join)(this.distDir, 'server', `${_constants.SUBRESOURCE_INTEGRITY_MANIFEST}.json`); + const pathJs = (0, _path.join)(this.distDir, 'server', `${_constants.SUBRESOURCE_INTEGRITY_MANIFEST}.js`); + this.pendingCacheDeletes.push(pathJson); + this.pendingCacheDeletes.push(pathJs); + (0, _writeatomic.writeFileAtomic)(pathJson, JSON.stringify(sriManifest, null, 2)); + (0, _writeatomic.writeFileAtomic)(pathJs, `self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(JSON.stringify(sriManifest))}`); + } + loadBuildManifest(pageName, type = 'pages') { + this.buildManifests.set((0, _entrykey.getEntryKey)(type, 'server', pageName), readPartialManifestContent(this.distDir, _constants.BUILD_MANIFEST, pageName, type)); + } + loadClientBuildManifest(pageName, type = 'pages') { + this.clientBuildManifests.set((0, _entrykey.getEntryKey)(type, 'server', pageName), readPartialManifestContent(this.distDir, _constants.TURBOPACK_CLIENT_BUILD_MANIFEST, pageName, type)); + } + loadSriManifest(pageName, type = 'pages') { + if (!this.sriEnabled) return; + this.sriManifests.set((0, _entrykey.getEntryKey)(type, 'client', pageName), readPartialManifestContent(this.distDir, `${_constants.SUBRESOURCE_INTEGRITY_MANIFEST}.json`, pageName, type)); + } + mergeBuildManifests(manifests, lowPriorityFiles) { + const manifest = { + pages: { + '/_app': [] + }, + // Something in next.js depends on these to exist even for app dir rendering + devFiles: [], + polyfillFiles: [], + lowPriorityFiles, + rootMainFiles: [], + rootMainFilesTree: {}, + pagesChunkGroupBootstrapParams: {} + }; + for (const m of manifests){ + Object.assign(manifest.pages, m.pages); + if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles; + // polyfillFiles should always be the same, so we can overwrite instead of actually merging + if (m.polyfillFiles.length) manifest.polyfillFiles = m.polyfillFiles; + if (m.rootMainFilesTree) { + Object.assign(manifest.rootMainFilesTree, m.rootMainFilesTree); + } + if (m.pagesChunkGroupBootstrapParams) { + Object.assign(manifest.pagesChunkGroupBootstrapParams, m.pagesChunkGroupBootstrapParams); + } + if (m.chunkLoadingGlobal) manifest.chunkLoadingGlobal = m.chunkLoadingGlobal; + } + manifest.pages = sortObjectByKey(manifest.pages); + return manifest; + } + mergeClientBuildManifests(manifests, rewrites, sortedPageKeys) { + const manifest = { + __rewrites: rewrites, + sortedPages: sortedPageKeys + }; + for (const m of manifests){ + Object.assign(manifest, m); + } + return sortObjectByKey(manifest); + } + writeInterceptionRouteRewriteManifest(devRewrites, productionRewrites) { + const rewrites = productionRewrites ?? { + ...devRewrites, + beforeFiles: (devRewrites?.beforeFiles ?? []).map(_buildmanifestpluginutils.processRoute), + afterFiles: (devRewrites?.afterFiles ?? []).map(_buildmanifestpluginutils.processRoute), + fallback: (devRewrites?.fallback ?? []).map(_buildmanifestpluginutils.processRoute) + }; + const interceptionRewrites = JSON.stringify(rewrites.beforeFiles.filter(require('../../../lib/is-interception-route-rewrite').isInterceptionRouteRewrite)); + if (this.cachedInterceptionRewrites === interceptionRewrites) { + return; + } + this.cachedInterceptionRewrites = interceptionRewrites; + const interceptionRewriteManifestPath = (0, _path.join)(this.distDir, 'server', `${_constants.INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`); + this.pendingCacheDeletes.push(interceptionRewriteManifestPath); + (0, _writeatomic.writeFileAtomic)(interceptionRewriteManifestPath, `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(interceptionRewrites)};`); + } + writeBuildManifest(lowPriorityFiles) { + if (!this.buildManifests.takeChanged()) { + return; + } + const buildManifest = this.mergeBuildManifests(this.buildManifests.values(), lowPriorityFiles); + const buildManifestPath = (0, _path.join)(this.distDir, _constants.BUILD_MANIFEST); + const middlewareBuildManifestPath = (0, _path.join)(this.distDir, 'server', `${_constants.MIDDLEWARE_BUILD_MANIFEST}.js`); + this.pendingCacheDeletes.push(buildManifestPath); + this.pendingCacheDeletes.push(middlewareBuildManifestPath); + (0, _writeatomic.writeFileAtomic)(buildManifestPath, JSON.stringify(buildManifest, null, 2)); + (0, _writeatomic.writeFileAtomic)(middlewareBuildManifestPath, (0, _buildmanifestpluginutils.createEdgeRuntimeManifest)(buildManifest)); + // Write fallback build manifest + const fallbackBuildManifest = this.mergeBuildManifests([ + this.buildManifests.get((0, _entrykey.getEntryKey)('pages', 'server', '_app')), + this.buildManifests.get((0, _entrykey.getEntryKey)('pages', 'server', '_error')) + ].filter(Boolean), lowPriorityFiles); + const fallbackBuildManifestPath = (0, _path.join)(this.distDir, `fallback-${_constants.BUILD_MANIFEST}`); + this.pendingCacheDeletes.push(fallbackBuildManifestPath); + (0, _writeatomic.writeFileAtomic)(fallbackBuildManifestPath, JSON.stringify(fallbackBuildManifest, null, 2)); + } + writeClientBuildManifest(entrypoints, devRewrites, productionRewrites) { + const rewrites = (0, _buildmanifestpluginutils.normalizeRewritesForBuildManifest)(productionRewrites ?? { + ...devRewrites, + beforeFiles: (devRewrites?.beforeFiles ?? []).map(_buildmanifestpluginutils.processRoute), + afterFiles: (devRewrites?.afterFiles ?? []).map(_buildmanifestpluginutils.processRoute), + fallback: (devRewrites?.fallback ?? []).map(_buildmanifestpluginutils.processRoute) + }); + const pagesKeys = [ + ...entrypoints.page.keys() + ]; + if (entrypoints.global.app) { + pagesKeys.push('/_app'); + } + if (entrypoints.global.error) { + pagesKeys.push('/_error'); + } + const sortedPageKeys = (0, _utils.getSortedRoutes)(pagesKeys); + let buildManifestPath = _path.posix.join(_constants.CLIENT_STATIC_FILES_PATH, this.buildId, '_buildManifest.js'); + let ssgManifestPath = _path.posix.join(_constants.CLIENT_STATIC_FILES_PATH, this.buildId, '_ssgManifest.js'); + if (this.dev && !this.clientBuildManifests.takeChanged({ + rewrites, + sortedPageKeys + })) { + return [ + buildManifestPath, + ssgManifestPath + ]; + } + const clientBuildManifest = this.mergeClientBuildManifests(this.clientBuildManifests.values(), rewrites, sortedPageKeys); + // Expose each route's bootstrap params and the chunk-loading global to the client + // so `route-loader` can instantiate a navigated page's entry module. The server + // stores params as raw JSON per route. + const pageBootstrapParams = {}; + let chunkLoadingGlobal; + for (const [key, m] of this.buildManifests.entries()){ + // Only the pages-router `route-loader` reads `__TURBOPACK_PAGE_BOOTSTRAP`. App routes + // navigate via flight and never use it, so skip app entries to keep `_buildManifest.js` + // (loaded on every page) small. + if ((0, _entrykey.splitEntryKey)(key).type !== 'pages') continue; + if (m.chunkLoadingGlobal) chunkLoadingGlobal = m.chunkLoadingGlobal; + for (const [route, params] of Object.entries(m.pagesChunkGroupBootstrapParams ?? {})){ + pageBootstrapParams[route] = params; + } + } + // Only emit the bootstrap globals when a route actually inlined its bootstrap (shared runtime + // enabled). + const hasBootstrapParams = Object.keys(pageBootstrapParams).length > 0; + const clientBuildManifestJs = `self.__BUILD_MANIFEST = ${JSON.stringify(clientBuildManifest, null, 2)};` + (hasBootstrapParams ? `self.__TURBOPACK_PAGE_BOOTSTRAP = ${JSON.stringify(pageBootstrapParams)};` + (chunkLoadingGlobal ? `self.__TURBOPACK_CHUNK_LOADING_GLOBAL = ${JSON.stringify(chunkLoadingGlobal)};` : '') : '') + `self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`; + (0, _writeatomic.writeFileAtomic)((0, _path.join)(this.distDir, buildManifestPath), clientBuildManifestJs); + // This is just an empty placeholder, the actual manifest is written after prerendering in + // packages/next/src/build/index.ts + (0, _writeatomic.writeFileAtomic)((0, _path.join)(this.distDir, ssgManifestPath), _buildmanifestpluginutils.srcEmptySsgManifest); + return [ + buildManifestPath, + ssgManifestPath + ]; + } + loadFontManifest(pageName, type = 'pages') { + this.fontManifests.set((0, _entrykey.getEntryKey)(type, 'server', pageName), readPartialManifestContent(this.distDir, `${_constants.NEXT_FONT_MANIFEST}.json`, pageName, type)); + } + mergeFontManifests(manifests) { + const manifest = { + app: {}, + appUsingSizeAdjust: false, + pages: {}, + pagesUsingSizeAdjust: false + }; + for (const m of manifests){ + Object.assign(manifest.app, m.app); + Object.assign(manifest.pages, m.pages); + manifest.appUsingSizeAdjust = manifest.appUsingSizeAdjust || m.appUsingSizeAdjust; + manifest.pagesUsingSizeAdjust = manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust; + } + manifest.app = sortObjectByKey(manifest.app); + manifest.pages = sortObjectByKey(manifest.pages); + return manifest; + } + async writeNextFontManifest() { + if (!this.fontManifests.takeChanged()) { + return; + } + const fontManifest = this.mergeFontManifests(this.fontManifests.values()); + const json = JSON.stringify(fontManifest, null, 2); + const fontManifestJsonPath = (0, _path.join)(this.distDir, 'server', `${_constants.NEXT_FONT_MANIFEST}.json`); + const fontManifestJsPath = (0, _path.join)(this.distDir, 'server', `${_constants.NEXT_FONT_MANIFEST}.js`); + this.pendingCacheDeletes.push(fontManifestJsonPath); + this.pendingCacheDeletes.push(fontManifestJsPath); + (0, _writeatomic.writeFileAtomic)(fontManifestJsonPath, json); + (0, _writeatomic.writeFileAtomic)(fontManifestJsPath, `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`); + } + /** + * @returns If the manifest was written or not + */ loadMiddlewareManifest(pageName, type) { + const middlewareManifestPath = getManifestPath(pageName, this.distDir, _constants.MIDDLEWARE_MANIFEST, type, true); + // middlewareManifest is actually "edge manifest" and not all routes are edge runtime. If it is not written we skip it. + if (!(0, _fs.existsSync)(middlewareManifestPath)) { + return false; + } + this.middlewareManifests.set((0, _entrykey.getEntryKey)(type === 'middleware' || type === 'instrumentation' ? 'root' : type, 'server', pageName), readPartialManifestContent(this.distDir, _constants.MIDDLEWARE_MANIFEST, pageName, type)); + return true; + } + getMiddlewareManifest(key) { + return this.middlewareManifests.get(key); + } + deleteMiddlewareManifest(key) { + return this.middlewareManifests.delete(key); + } + mergeMiddlewareManifests(manifests) { + const manifest = { + version: 3, + middleware: {}, + sortedMiddleware: [], + functions: {} + }; + let instrumentation = undefined; + for (const m of manifests){ + Object.assign(manifest.functions, m.functions); + Object.assign(manifest.middleware, m.middleware); + if (m.instrumentation) { + instrumentation = m.instrumentation; + } + } + manifest.functions = sortObjectByKey(manifest.functions); + manifest.middleware = sortObjectByKey(manifest.middleware); + const updateFunctionDefinition = (fun)=>{ + return { + ...fun, + files: [ + ...instrumentation?.files ?? [], + ...fun.files + ] + }; + }; + for (const key of Object.keys(manifest.middleware)){ + const value = manifest.middleware[key]; + manifest.middleware[key] = updateFunctionDefinition(value); + } + for (const key of Object.keys(manifest.functions)){ + const value = manifest.functions[key]; + manifest.functions[key] = updateFunctionDefinition(value); + } + for (const fun of Object.values(manifest.functions).concat(Object.values(manifest.middleware))){ + for (const matcher of fun.matchers){ + if (!matcher.regexp) { + matcher.regexp = (0, _routematchutils.safePathToRegexp)(matcher.originalSource, [], { + delimiter: '/', + sensitive: false, + strict: true + }).source.replaceAll('\\/', '/'); + } + } + } + manifest.sortedMiddleware = Object.keys(manifest.middleware); + return manifest; + } + writeMiddlewareManifest() { + let clientMiddlewareManifestPath = _path.posix.join(_constants.CLIENT_STATIC_FILES_PATH, this.buildId, _constants.TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST); + if (this.dev && !this.middlewareManifests.takeChanged()) { + return { + clientMiddlewareManifestPath + }; + } + const middlewareManifest = this.mergeMiddlewareManifests(this.middlewareManifests.values()); + // Server middleware manifest + // Normalize regexes as it uses path-to-regexp + for(const key in middlewareManifest.middleware){ + middlewareManifest.middleware[key].matchers.forEach((matcher)=>{ + if (!matcher.regexp.startsWith('^')) { + const parsedPage = (0, _trytoparsepath.tryToParsePath)(matcher.regexp); + if (parsedPage.error || !parsedPage.regexStr) { + throw new Error(`Invalid source: ${matcher.regexp}`); + } + matcher.regexp = parsedPage.regexStr; + } + }); + } + const middlewareManifestPath = (0, _path.join)(this.distDir, 'server', _constants.MIDDLEWARE_MANIFEST); + this.pendingCacheDeletes.push(middlewareManifestPath); + (0, _writeatomic.writeFileAtomic)(middlewareManifestPath, JSON.stringify(middlewareManifest, null, 2)); + // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts + // writes the manifest again for builds. + const matchers = middlewareManifest?.middleware['/']?.matchers || []; + const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(matchers, null, 2)};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`; + this.pendingCacheDeletes.push(clientMiddlewareManifestPath); + (0, _writeatomic.writeFileAtomic)((0, _path.join)(this.distDir, clientMiddlewareManifestPath), clientMiddlewareManifestJs); + return { + clientMiddlewareManifestPath + }; + } + loadPagesManifest(pageName) { + this.pagesManifests.set((0, _entrykey.getEntryKey)('pages', 'server', pageName), readPartialManifestContent(this.distDir, _constants.PAGES_MANIFEST, pageName)); + } + mergePagesManifests(manifests) { + const manifest = {}; + for (const m of manifests){ + Object.assign(manifest, m); + } + return sortObjectByKey(manifest); + } + mergeSriManifests(manifests) { + const manifest = {}; + for (const m of manifests){ + Object.assign(manifest, m); + } + return sortObjectByKey(manifest); + } + writePagesManifest() { + if (!this.pagesManifests.takeChanged()) { + return; + } + const pagesManifest = this.mergePagesManifests(this.pagesManifests.values()); + const pagesManifestPath = (0, _path.join)(this.distDir, 'server', _constants.PAGES_MANIFEST); + this.pendingCacheDeletes.push(pagesManifestPath); + (0, _writeatomic.writeFileAtomic)(pagesManifestPath, JSON.stringify(pagesManifest, null, 2)); + } + writeManifests({ devRewrites, productionRewrites, entrypoints }) { + this.writeActionManifest(); + this.writeAppPathsManifest(); + const lowPriorityFiles = this.writeClientBuildManifest(entrypoints, devRewrites, productionRewrites); + const { clientMiddlewareManifestPath } = this.writeMiddlewareManifest(); + this.writeBuildManifest([ + ...lowPriorityFiles, + clientMiddlewareManifestPath + ]); + this.writeInterceptionRouteRewriteManifest(devRewrites, productionRewrites); + this.writeNextFontManifest(); + this.writePagesManifest(); + this.writeSriManifest(); + // Flush all queued cache deletions in a single require.cache scan + if (this.pendingCacheDeletes.length > 0) { + (0, _requirecache.deleteCache)(this.pendingCacheDeletes); + this.pendingCacheDeletes = []; + } + } +} +function sortObjectByKey(obj) { + return Object.keys(obj).sort().reduce((acc, key)=>{ + acc[key] = obj[key]; + return acc; + }, {}); +} + +//# sourceMappingURL=manifest-loader.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.js.map b/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.js.map new file mode 100644 index 0000000000000000000000000000000000000000..88a57d509736906b705e1d5c59709c59af4b9858 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/manifest-loader.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/turbopack/manifest-loader.ts"],"sourcesContent":["import type {\n EdgeFunctionDefinition,\n MiddlewareManifest,\n} from '../../../build/webpack/plugins/middleware-plugin'\nimport type { BuildManifest } from '../../../server/get-page-files'\nimport type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin'\nimport type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { REACT_LOADABLE_MANIFEST } from '../constants'\nimport {\n APP_PATHS_MANIFEST,\n BUILD_MANIFEST,\n CLIENT_STATIC_FILES_PATH,\n INTERCEPTION_ROUTE_REWRITE_MANIFEST,\n MIDDLEWARE_BUILD_MANIFEST,\n MIDDLEWARE_MANIFEST,\n NEXT_FONT_MANIFEST,\n PAGES_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,\n} from '../constants'\nimport { join, posix } from 'path'\nimport { readFileSync } from 'fs'\nimport type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'\nimport { deleteCache } from '../../../server/dev/require-cache'\nimport { writeFileAtomic } from '../../../lib/fs/write-atomic'\nimport getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'\nimport { getEntryKey, splitEntryKey, type EntryKey } from './entry-key'\nimport type { CustomRoutes } from '../../../lib/load-custom-routes'\nimport { getSortedRoutes } from '../router/utils'\nimport { existsSync } from 'fs'\nimport {\n addMetadataIdToRoute,\n addRouteSuffix,\n removeRouteSuffix,\n} from '../../../server/dev/turbopack-utils'\nimport { tryToParsePath } from '../../../lib/try-to-parse-path'\nimport { safePathToRegexp } from '../router/utils/route-match-utils'\nimport type { Entrypoints } from '../../../build/swc/types'\nimport {\n normalizeRewritesForBuildManifest,\n type ClientBuildManifest,\n srcEmptySsgManifest,\n processRoute,\n createEdgeRuntimeManifest,\n} from '../../../build/webpack/plugins/build-manifest-plugin-utils'\nimport type { SubresourceIntegrityManifest } from '../../../build'\n\ninterface InstrumentationDefinition {\n files: string[]\n name: 'instrumentation'\n}\n\ntype TurbopackMiddlewareManifest = MiddlewareManifest & {\n instrumentation?: InstrumentationDefinition\n}\n\ntype ManifestName =\n | typeof MIDDLEWARE_MANIFEST\n | typeof BUILD_MANIFEST\n | typeof PAGES_MANIFEST\n | typeof APP_PATHS_MANIFEST\n | `${typeof SERVER_REFERENCE_MANIFEST}.json`\n | `${typeof SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n | `${typeof NEXT_FONT_MANIFEST}.json`\n | typeof REACT_LOADABLE_MANIFEST\n | typeof TURBOPACK_CLIENT_BUILD_MANIFEST\n\nconst getManifestPath = (\n page: string,\n distDir: string,\n name: ManifestName,\n type: string,\n firstCall: boolean\n) => {\n let manifestPath = posix.join(\n distDir,\n `server`,\n type,\n type === 'middleware' || type === 'instrumentation'\n ? ''\n : type === 'app'\n ? page\n : getAssetPathFromRoute(page),\n name\n )\n\n if (firstCall) {\n const isSitemapRoute = /[\\\\/]sitemap(.xml)?\\/route$/.test(page)\n // Check the ambiguity of /sitemap and /sitemap.xml\n if (isSitemapRoute && !existsSync(manifestPath)) {\n manifestPath = getManifestPath(\n page.replace(/\\/sitemap\\/route$/, '/sitemap.xml/route'),\n distDir,\n name,\n type,\n false\n )\n }\n // existsSync is faster than using the async version\n if (!existsSync(manifestPath) && page.endsWith('/route')) {\n // TODO: Improve implementation of metadata routes, currently it requires this extra check for the variants of the files that can be written.\n let basePage = removeRouteSuffix(page)\n // For sitemap.xml routes with generateSitemaps, the manifest is at\n // /sitemap/[__metadata_id__]/route (without .xml), because the route\n // handler serves at /sitemap/[id] not /sitemap.xml/[id]\n if (basePage.endsWith('/sitemap.xml')) {\n basePage = basePage.slice(0, -'.xml'.length)\n }\n let metadataPage = addRouteSuffix(addMetadataIdToRoute(basePage))\n manifestPath = getManifestPath(metadataPage, distDir, name, type, false)\n }\n }\n\n return manifestPath\n}\n\nfunction readPartialManifestContent(\n distDir: string,\n name: ManifestName,\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation' = 'pages'\n): string {\n const page = pageName\n const manifestPath = getManifestPath(page, distDir, name, type, true)\n return readFileSync(posix.join(manifestPath), 'utf-8')\n}\n\n/// Helper class that stores a map of manifests and tracks if they have changed\n/// since the last time they were written to disk. This is used to avoid\n/// unnecessary writes to disk.\nclass ManifestsMap {\n private rawMap = new Map()\n private map = new Map()\n private extraInvalidationKey: string | undefined = undefined\n private changed = true\n\n set(key: K, value: string) {\n if (this.rawMap.get(key) === value) return\n this.changed = true\n this.rawMap.set(key, value)\n this.map.set(key, JSON.parse(value))\n }\n\n delete(key: K) {\n if (this.map.has(key)) {\n this.changed = true\n this.rawMap.delete(key)\n this.map.delete(key)\n }\n }\n\n get(key: K) {\n return this.map.get(key)\n }\n\n takeChanged(extraInvalidationKey?: any) {\n let changed = this.changed\n if (extraInvalidationKey !== undefined) {\n const stringified = JSON.stringify(extraInvalidationKey)\n if (this.extraInvalidationKey !== stringified) {\n this.extraInvalidationKey = stringified\n changed = true\n }\n }\n this.changed = false\n return changed\n }\n\n values() {\n return this.map.values()\n }\n\n entries() {\n return this.map.entries()\n }\n}\n\nexport class TurbopackManifestLoader {\n private actionManifests: ManifestsMap =\n new ManifestsMap()\n private appPathsManifests: ManifestsMap =\n new ManifestsMap()\n private buildManifests: ManifestsMap =\n new ManifestsMap()\n private clientBuildManifests: ManifestsMap =\n new ManifestsMap()\n private fontManifests: ManifestsMap =\n new ManifestsMap()\n private middlewareManifests: ManifestsMap<\n EntryKey,\n TurbopackMiddlewareManifest\n > = new ManifestsMap()\n private pagesManifests: ManifestsMap =\n new ManifestsMap()\n private sriManifests: ManifestsMap =\n new ManifestsMap()\n private encryptionKey: string\n /// interceptionRewrites that have been written to disk\n /// This is used to avoid unnecessary writes if the rewrites haven't changed\n private cachedInterceptionRewrites: string | undefined = undefined\n private pendingCacheDeletes: string[] = []\n\n private readonly distDir: string\n private readonly buildId: string\n private readonly dev: boolean\n private readonly sriEnabled: boolean\n\n constructor({\n distDir,\n buildId,\n encryptionKey,\n dev,\n sriEnabled,\n }: {\n buildId: string\n distDir: string\n encryptionKey: string\n dev: boolean\n sriEnabled: boolean\n }) {\n this.distDir = distDir\n this.buildId = buildId\n this.encryptionKey = encryptionKey\n this.dev = dev\n this.sriEnabled = sriEnabled\n }\n\n delete(key: EntryKey) {\n this.actionManifests.delete(key)\n this.appPathsManifests.delete(key)\n this.buildManifests.delete(key)\n this.clientBuildManifests.delete(key)\n this.fontManifests.delete(key)\n this.middlewareManifests.delete(key)\n this.pagesManifests.delete(key)\n }\n\n loadActionManifest(pageName: string): void {\n this.actionManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SERVER_REFERENCE_MANIFEST}.json`,\n pageName,\n 'app'\n )\n )\n }\n\n private mergeActionManifests(manifests: Iterable) {\n type ActionEntries = ActionManifest['edge' | 'node']\n const manifest: ActionManifest = {\n node: {},\n edge: {},\n encryptionKey: this.encryptionKey,\n }\n\n function mergeActionIds(\n actionEntries: ActionEntries,\n other: ActionEntries\n ): void {\n for (const key in other) {\n const action = (actionEntries[key] ??= {\n workers: {},\n })\n action.filename = other[key].filename\n action.exportedName = other[key].exportedName\n Object.assign(action.workers, other[key].workers)\n }\n }\n\n for (const m of manifests) {\n mergeActionIds(manifest.node, m.node)\n mergeActionIds(manifest.edge, m.edge)\n }\n for (const key in manifest.node) {\n const entry = manifest.node[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n for (const key in manifest.edge) {\n const entry = manifest.edge[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n\n return manifest\n }\n\n private writeActionManifest(): void {\n if (!this.actionManifests.takeChanged()) {\n return\n }\n const actionManifest = this.mergeActionManifests(\n this.actionManifests.values()\n )\n const actionManifestJsonPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.json`\n )\n const actionManifestJsPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.js`\n )\n const json = JSON.stringify(actionManifest, null, 2)\n this.pendingCacheDeletes.push(actionManifestJsonPath)\n this.pendingCacheDeletes.push(actionManifestJsPath)\n writeFileAtomic(actionManifestJsonPath, json)\n writeFileAtomic(\n actionManifestJsPath,\n `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n loadAppPathsManifest(pageName: string): void {\n this.appPathsManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n APP_PATHS_MANIFEST,\n pageName,\n 'app'\n )\n )\n }\n\n private writeAppPathsManifest(): void {\n if (!this.appPathsManifests.takeChanged()) {\n return\n }\n const appPathsManifest = this.mergePagesManifests(\n this.appPathsManifests.values()\n )\n const appPathsManifestPath = join(\n this.distDir,\n 'server',\n APP_PATHS_MANIFEST\n )\n this.pendingCacheDeletes.push(appPathsManifestPath)\n writeFileAtomic(\n appPathsManifestPath,\n JSON.stringify(appPathsManifest, null, 2)\n )\n }\n\n private writeSriManifest(): void {\n if (!this.sriEnabled || !this.sriManifests.takeChanged()) {\n return\n }\n const sriManifest = this.mergeSriManifests(this.sriManifests.values())\n const pathJson = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n )\n const pathJs = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(pathJson)\n this.pendingCacheDeletes.push(pathJs)\n writeFileAtomic(pathJson, JSON.stringify(sriManifest, null, 2))\n writeFileAtomic(\n pathJs,\n `self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(\n JSON.stringify(sriManifest)\n )}`\n )\n }\n\n loadBuildManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.buildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(this.distDir, BUILD_MANIFEST, pageName, type)\n )\n }\n\n loadClientBuildManifest(\n pageName: string,\n type: 'app' | 'pages' = 'pages'\n ): void {\n this.clientBuildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n pageName,\n type\n )\n )\n }\n\n loadSriManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n if (!this.sriEnabled) return\n this.sriManifests.set(\n getEntryKey(type, 'client', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeBuildManifests(\n manifests: Iterable,\n lowPriorityFiles: string[]\n ) {\n const manifest: Partial & Pick = {\n pages: {\n '/_app': [],\n },\n // Something in next.js depends on these to exist even for app dir rendering\n devFiles: [],\n polyfillFiles: [],\n lowPriorityFiles,\n rootMainFiles: [],\n rootMainFilesTree: {},\n pagesChunkGroupBootstrapParams: {},\n }\n for (const m of manifests) {\n Object.assign(manifest.pages, m.pages)\n if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles\n // polyfillFiles should always be the same, so we can overwrite instead of actually merging\n if (m.polyfillFiles.length) manifest.polyfillFiles = m.polyfillFiles\n if (m.rootMainFilesTree) {\n Object.assign(manifest.rootMainFilesTree!, m.rootMainFilesTree)\n }\n if (m.pagesChunkGroupBootstrapParams) {\n Object.assign(\n manifest.pagesChunkGroupBootstrapParams!,\n m.pagesChunkGroupBootstrapParams\n )\n }\n if (m.chunkLoadingGlobal)\n manifest.chunkLoadingGlobal = m.chunkLoadingGlobal\n }\n manifest.pages = sortObjectByKey(manifest.pages) as BuildManifest['pages']\n return manifest\n }\n\n private mergeClientBuildManifests(\n manifests: Iterable,\n rewrites: CustomRoutes['rewrites'],\n sortedPageKeys: string[]\n ): ClientBuildManifest {\n const manifest = {\n __rewrites: rewrites as any,\n sortedPages: sortedPageKeys,\n }\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writeInterceptionRouteRewriteManifest(\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): void {\n const rewrites = productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n\n const interceptionRewrites = JSON.stringify(\n rewrites.beforeFiles.filter(\n (\n require('../../../lib/is-interception-route-rewrite') as typeof import('../../../lib/is-interception-route-rewrite')\n ).isInterceptionRouteRewrite\n )\n )\n\n if (this.cachedInterceptionRewrites === interceptionRewrites) {\n return\n }\n this.cachedInterceptionRewrites = interceptionRewrites\n\n const interceptionRewriteManifestPath = join(\n this.distDir,\n 'server',\n `${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(interceptionRewriteManifestPath)\n\n writeFileAtomic(\n interceptionRewriteManifestPath,\n `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(\n interceptionRewrites\n )};`\n )\n }\n\n private writeBuildManifest(lowPriorityFiles: string[]): void {\n if (!this.buildManifests.takeChanged()) {\n return\n }\n const buildManifest = this.mergeBuildManifests(\n this.buildManifests.values(),\n lowPriorityFiles\n )\n\n const buildManifestPath = join(this.distDir, BUILD_MANIFEST)\n const middlewareBuildManifestPath = join(\n this.distDir,\n 'server',\n `${MIDDLEWARE_BUILD_MANIFEST}.js`\n )\n\n this.pendingCacheDeletes.push(buildManifestPath)\n this.pendingCacheDeletes.push(middlewareBuildManifestPath)\n writeFileAtomic(buildManifestPath, JSON.stringify(buildManifest, null, 2))\n writeFileAtomic(\n middlewareBuildManifestPath,\n createEdgeRuntimeManifest(buildManifest)\n )\n\n // Write fallback build manifest\n const fallbackBuildManifest = this.mergeBuildManifests(\n [\n this.buildManifests.get(getEntryKey('pages', 'server', '_app')),\n this.buildManifests.get(getEntryKey('pages', 'server', '_error')),\n ].filter(Boolean) as BuildManifest[],\n lowPriorityFiles\n )\n const fallbackBuildManifestPath = join(\n this.distDir,\n `fallback-${BUILD_MANIFEST}`\n )\n this.pendingCacheDeletes.push(fallbackBuildManifestPath)\n writeFileAtomic(\n fallbackBuildManifestPath,\n JSON.stringify(fallbackBuildManifest, null, 2)\n )\n }\n\n private writeClientBuildManifest(\n entrypoints: Entrypoints,\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): string[] {\n const rewrites = normalizeRewritesForBuildManifest(\n productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n )\n\n const pagesKeys = [...entrypoints.page.keys()]\n if (entrypoints.global.app) {\n pagesKeys.push('/_app')\n }\n if (entrypoints.global.error) {\n pagesKeys.push('/_error')\n }\n\n const sortedPageKeys = getSortedRoutes(pagesKeys)\n\n let buildManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_buildManifest.js'\n )\n let ssgManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_ssgManifest.js'\n )\n\n if (\n this.dev &&\n !this.clientBuildManifests.takeChanged({ rewrites, sortedPageKeys })\n ) {\n return [buildManifestPath, ssgManifestPath]\n }\n\n const clientBuildManifest = this.mergeClientBuildManifests(\n this.clientBuildManifests.values(),\n rewrites,\n sortedPageKeys\n )\n\n // Expose each route's bootstrap params and the chunk-loading global to the client\n // so `route-loader` can instantiate a navigated page's entry module. The server\n // stores params as raw JSON per route.\n const pageBootstrapParams: Record = {}\n let chunkLoadingGlobal: string | undefined\n for (const [key, m] of this.buildManifests.entries()) {\n // Only the pages-router `route-loader` reads `__TURBOPACK_PAGE_BOOTSTRAP`. App routes\n // navigate via flight and never use it, so skip app entries to keep `_buildManifest.js`\n // (loaded on every page) small.\n if (splitEntryKey(key).type !== 'pages') continue\n if (m.chunkLoadingGlobal) chunkLoadingGlobal = m.chunkLoadingGlobal\n for (const [route, params] of Object.entries(\n m.pagesChunkGroupBootstrapParams ?? {}\n )) {\n pageBootstrapParams[route] = params\n }\n }\n\n // Only emit the bootstrap globals when a route actually inlined its bootstrap (shared runtime\n // enabled).\n const hasBootstrapParams = Object.keys(pageBootstrapParams).length > 0\n const clientBuildManifestJs =\n `self.__BUILD_MANIFEST = ${JSON.stringify(clientBuildManifest, null, 2)};` +\n (hasBootstrapParams\n ? `self.__TURBOPACK_PAGE_BOOTSTRAP = ${JSON.stringify(pageBootstrapParams)};` +\n (chunkLoadingGlobal\n ? `self.__TURBOPACK_CHUNK_LOADING_GLOBAL = ${JSON.stringify(\n chunkLoadingGlobal\n )};`\n : '')\n : '') +\n `self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`\n\n writeFileAtomic(\n join(this.distDir, buildManifestPath),\n clientBuildManifestJs\n )\n // This is just an empty placeholder, the actual manifest is written after prerendering in\n // packages/next/src/build/index.ts\n writeFileAtomic(join(this.distDir, ssgManifestPath), srcEmptySsgManifest)\n\n return [buildManifestPath, ssgManifestPath]\n }\n\n loadFontManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.fontManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${NEXT_FONT_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeFontManifests(manifests: Iterable) {\n const manifest: NextFontManifest = {\n app: {},\n appUsingSizeAdjust: false,\n pages: {},\n pagesUsingSizeAdjust: false,\n }\n for (const m of manifests) {\n Object.assign(manifest.app, m.app)\n Object.assign(manifest.pages, m.pages)\n\n manifest.appUsingSizeAdjust =\n manifest.appUsingSizeAdjust || m.appUsingSizeAdjust\n manifest.pagesUsingSizeAdjust =\n manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust\n }\n manifest.app = sortObjectByKey(manifest.app)\n manifest.pages = sortObjectByKey(manifest.pages)\n return manifest\n }\n\n private async writeNextFontManifest(): Promise {\n if (!this.fontManifests.takeChanged()) {\n return\n }\n const fontManifest = this.mergeFontManifests(this.fontManifests.values())\n const json = JSON.stringify(fontManifest, null, 2)\n\n const fontManifestJsonPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.json`\n )\n const fontManifestJsPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(fontManifestJsonPath)\n this.pendingCacheDeletes.push(fontManifestJsPath)\n writeFileAtomic(fontManifestJsonPath, json)\n writeFileAtomic(\n fontManifestJsPath,\n `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n /**\n * @returns If the manifest was written or not\n */\n loadMiddlewareManifest(\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation'\n ): boolean {\n const middlewareManifestPath = getManifestPath(\n pageName,\n this.distDir,\n MIDDLEWARE_MANIFEST,\n type,\n true\n )\n\n // middlewareManifest is actually \"edge manifest\" and not all routes are edge runtime. If it is not written we skip it.\n if (!existsSync(middlewareManifestPath)) {\n return false\n }\n\n this.middlewareManifests.set(\n getEntryKey(\n type === 'middleware' || type === 'instrumentation' ? 'root' : type,\n 'server',\n pageName\n ),\n readPartialManifestContent(\n this.distDir,\n MIDDLEWARE_MANIFEST,\n pageName,\n type\n )\n )\n\n return true\n }\n\n getMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.get(key)\n }\n\n deleteMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.delete(key)\n }\n\n private mergeMiddlewareManifests(\n manifests: Iterable\n ): MiddlewareManifest {\n const manifest: MiddlewareManifest = {\n version: 3,\n middleware: {},\n sortedMiddleware: [],\n functions: {},\n }\n let instrumentation: InstrumentationDefinition | undefined = undefined\n for (const m of manifests) {\n Object.assign(manifest.functions, m.functions)\n Object.assign(manifest.middleware, m.middleware)\n if (m.instrumentation) {\n instrumentation = m.instrumentation\n }\n }\n manifest.functions = sortObjectByKey(manifest.functions)\n manifest.middleware = sortObjectByKey(manifest.middleware)\n const updateFunctionDefinition = (\n fun: EdgeFunctionDefinition\n ): EdgeFunctionDefinition => {\n return {\n ...fun,\n files: [...(instrumentation?.files ?? []), ...fun.files],\n }\n }\n for (const key of Object.keys(manifest.middleware)) {\n const value = manifest.middleware[key]\n manifest.middleware[key] = updateFunctionDefinition(value)\n }\n for (const key of Object.keys(manifest.functions)) {\n const value = manifest.functions[key]\n manifest.functions[key] = updateFunctionDefinition(value)\n }\n for (const fun of Object.values(manifest.functions).concat(\n Object.values(manifest.middleware)\n )) {\n for (const matcher of fun.matchers) {\n if (!matcher.regexp) {\n matcher.regexp = safePathToRegexp(matcher.originalSource, [], {\n delimiter: '/',\n sensitive: false,\n strict: true,\n }).source.replaceAll('\\\\/', '/')\n }\n }\n }\n manifest.sortedMiddleware = Object.keys(manifest.middleware)\n\n return manifest\n }\n\n private writeMiddlewareManifest(): {\n clientMiddlewareManifestPath: string\n } {\n let clientMiddlewareManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST\n )\n\n if (this.dev && !this.middlewareManifests.takeChanged()) {\n return {\n clientMiddlewareManifestPath,\n }\n }\n const middlewareManifest = this.mergeMiddlewareManifests(\n this.middlewareManifests.values()\n )\n\n // Server middleware manifest\n\n // Normalize regexes as it uses path-to-regexp\n for (const key in middlewareManifest.middleware) {\n middlewareManifest.middleware[key].matchers.forEach((matcher) => {\n if (!matcher.regexp.startsWith('^')) {\n const parsedPage = tryToParsePath(matcher.regexp)\n if (parsedPage.error || !parsedPage.regexStr) {\n throw new Error(`Invalid source: ${matcher.regexp}`)\n }\n matcher.regexp = parsedPage.regexStr\n }\n })\n }\n\n const middlewareManifestPath = join(\n this.distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n this.pendingCacheDeletes.push(middlewareManifestPath)\n writeFileAtomic(\n middlewareManifestPath,\n JSON.stringify(middlewareManifest, null, 2)\n )\n\n // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts\n // writes the manifest again for builds.\n const matchers = middlewareManifest?.middleware['/']?.matchers || []\n\n const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(\n matchers,\n null,\n 2\n )};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`\n\n this.pendingCacheDeletes.push(clientMiddlewareManifestPath)\n writeFileAtomic(\n join(this.distDir, clientMiddlewareManifestPath),\n clientMiddlewareManifestJs\n )\n\n return {\n clientMiddlewareManifestPath,\n }\n }\n\n loadPagesManifest(pageName: string): void {\n this.pagesManifests.set(\n getEntryKey('pages', 'server', pageName),\n readPartialManifestContent(this.distDir, PAGES_MANIFEST, pageName)\n )\n }\n\n private mergePagesManifests(manifests: Iterable) {\n const manifest: PagesManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private mergeSriManifests(manifests: Iterable) {\n const manifest: SubresourceIntegrityManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writePagesManifest(): void {\n if (!this.pagesManifests.takeChanged()) {\n return\n }\n const pagesManifest = this.mergePagesManifests(this.pagesManifests.values())\n const pagesManifestPath = join(this.distDir, 'server', PAGES_MANIFEST)\n this.pendingCacheDeletes.push(pagesManifestPath)\n writeFileAtomic(pagesManifestPath, JSON.stringify(pagesManifest, null, 2))\n }\n\n writeManifests({\n devRewrites,\n productionRewrites,\n entrypoints,\n }: {\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n productionRewrites: CustomRoutes['rewrites'] | undefined\n entrypoints: Entrypoints\n }): void {\n this.writeActionManifest()\n this.writeAppPathsManifest()\n const lowPriorityFiles = this.writeClientBuildManifest(\n entrypoints,\n devRewrites,\n productionRewrites\n )\n const { clientMiddlewareManifestPath } = this.writeMiddlewareManifest()\n this.writeBuildManifest([...lowPriorityFiles, clientMiddlewareManifestPath])\n this.writeInterceptionRouteRewriteManifest(devRewrites, productionRewrites)\n this.writeNextFontManifest()\n this.writePagesManifest()\n\n this.writeSriManifest()\n\n // Flush all queued cache deletions in a single require.cache scan\n if (this.pendingCacheDeletes.length > 0) {\n deleteCache(this.pendingCacheDeletes)\n this.pendingCacheDeletes = []\n }\n }\n}\n\nfunction sortObjectByKey(obj: Record) {\n return Object.keys(obj)\n .sort()\n .reduce(\n (acc, key) => {\n acc[key] = obj[key]\n return acc\n },\n {} as Record\n )\n}\n"],"names":["TurbopackManifestLoader","getManifestPath","page","distDir","name","type","firstCall","manifestPath","posix","join","getAssetPathFromRoute","isSitemapRoute","test","existsSync","replace","endsWith","basePage","removeRouteSuffix","slice","length","metadataPage","addRouteSuffix","addMetadataIdToRoute","readPartialManifestContent","pageName","readFileSync","ManifestsMap","set","key","value","rawMap","get","changed","map","JSON","parse","delete","has","takeChanged","extraInvalidationKey","undefined","stringified","stringify","values","entries","Map","constructor","buildId","encryptionKey","dev","sriEnabled","actionManifests","appPathsManifests","buildManifests","clientBuildManifests","fontManifests","middlewareManifests","pagesManifests","sriManifests","cachedInterceptionRewrites","pendingCacheDeletes","loadActionManifest","getEntryKey","SERVER_REFERENCE_MANIFEST","mergeActionManifests","manifests","manifest","node","edge","mergeActionIds","actionEntries","other","action","workers","filename","exportedName","Object","assign","m","entry","sortObjectByKey","writeActionManifest","actionManifest","actionManifestJsonPath","actionManifestJsPath","json","push","writeFileAtomic","loadAppPathsManifest","APP_PATHS_MANIFEST","writeAppPathsManifest","appPathsManifest","mergePagesManifests","appPathsManifestPath","writeSriManifest","sriManifest","mergeSriManifests","pathJson","SUBRESOURCE_INTEGRITY_MANIFEST","pathJs","loadBuildManifest","BUILD_MANIFEST","loadClientBuildManifest","TURBOPACK_CLIENT_BUILD_MANIFEST","loadSriManifest","mergeBuildManifests","lowPriorityFiles","pages","devFiles","polyfillFiles","rootMainFiles","rootMainFilesTree","pagesChunkGroupBootstrapParams","chunkLoadingGlobal","mergeClientBuildManifests","rewrites","sortedPageKeys","__rewrites","sortedPages","writeInterceptionRouteRewriteManifest","devRewrites","productionRewrites","beforeFiles","processRoute","afterFiles","fallback","interceptionRewrites","filter","require","isInterceptionRouteRewrite","interceptionRewriteManifestPath","INTERCEPTION_ROUTE_REWRITE_MANIFEST","writeBuildManifest","buildManifest","buildManifestPath","middlewareBuildManifestPath","MIDDLEWARE_BUILD_MANIFEST","createEdgeRuntimeManifest","fallbackBuildManifest","Boolean","fallbackBuildManifestPath","writeClientBuildManifest","entrypoints","normalizeRewritesForBuildManifest","pagesKeys","keys","global","app","error","getSortedRoutes","CLIENT_STATIC_FILES_PATH","ssgManifestPath","clientBuildManifest","pageBootstrapParams","splitEntryKey","route","params","hasBootstrapParams","clientBuildManifestJs","srcEmptySsgManifest","loadFontManifest","NEXT_FONT_MANIFEST","mergeFontManifests","appUsingSizeAdjust","pagesUsingSizeAdjust","writeNextFontManifest","fontManifest","fontManifestJsonPath","fontManifestJsPath","loadMiddlewareManifest","middlewareManifestPath","MIDDLEWARE_MANIFEST","getMiddlewareManifest","deleteMiddlewareManifest","mergeMiddlewareManifests","version","middleware","sortedMiddleware","functions","instrumentation","updateFunctionDefinition","fun","files","concat","matcher","matchers","regexp","safePathToRegexp","originalSource","delimiter","sensitive","strict","source","replaceAll","writeMiddlewareManifest","clientMiddlewareManifestPath","TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST","middlewareManifest","forEach","startsWith","parsedPage","tryToParsePath","regexStr","Error","clientMiddlewareManifestJs","loadPagesManifest","PAGES_MANIFEST","writePagesManifest","pagesManifest","pagesManifestPath","writeManifests","deleteCache","obj","sort","reduce","acc"],"mappings":";;;;+BAoLaA;;;eAAAA;;;;2BA9JN;sBACqB;oBACC;8BAED;6BACI;gFACE;0BACwB;uBAE1B;gCAMzB;gCACwB;iCACE;0CAQ1B;AAuBP,MAAMC,kBAAkB,CACtBC,MACAC,SACAC,MACAC,MACAC;IAEA,IAAIC,eAAeC,WAAK,CAACC,IAAI,CAC3BN,SACA,CAAC,MAAM,CAAC,EACRE,MACAA,SAAS,gBAAgBA,SAAS,oBAC9B,KACAA,SAAS,QACPH,OACAQ,IAAAA,8BAAqB,EAACR,OAC5BE;IAGF,IAAIE,WAAW;QACb,MAAMK,iBAAiB,8BAA8BC,IAAI,CAACV;QAC1D,mDAAmD;QACnD,IAAIS,kBAAkB,CAACE,IAAAA,cAAU,EAACN,eAAe;YAC/CA,eAAeN,gBACbC,KAAKY,OAAO,CAAC,qBAAqB,uBAClCX,SACAC,MACAC,MACA;QAEJ;QACA,oDAAoD;QACpD,IAAI,CAACQ,IAAAA,cAAU,EAACN,iBAAiBL,KAAKa,QAAQ,CAAC,WAAW;YACxD,6IAA6I;YAC7I,IAAIC,WAAWC,IAAAA,iCAAiB,EAACf;YACjC,mEAAmE;YACnE,qEAAqE;YACrE,wDAAwD;YACxD,IAAIc,SAASD,QAAQ,CAAC,iBAAiB;gBACrCC,WAAWA,SAASE,KAAK,CAAC,GAAG,CAAC,OAAOC,MAAM;YAC7C;YACA,IAAIC,eAAeC,IAAAA,8BAAc,EAACC,IAAAA,oCAAoB,EAACN;YACvDT,eAAeN,gBAAgBmB,cAAcjB,SAASC,MAAMC,MAAM;QACpE;IACF;IAEA,OAAOE;AACT;AAEA,SAASgB,2BACPpB,OAAe,EACfC,IAAkB,EAClBoB,QAAgB,EAChBnB,OAA2D,OAAO;IAElE,MAAMH,OAAOsB;IACb,MAAMjB,eAAeN,gBAAgBC,MAAMC,SAASC,MAAMC,MAAM;IAChE,OAAOoB,IAAAA,gBAAY,EAACjB,WAAK,CAACC,IAAI,CAACF,eAAe;AAChD;AAEA,+EAA+E;AAC/E,wEAAwE;AACxE,+BAA+B;AAC/B,MAAMmB;IAMJC,IAAIC,GAAM,EAAEC,KAAa,EAAE;QACzB,IAAI,IAAI,CAACC,MAAM,CAACC,GAAG,CAACH,SAASC,OAAO;QACpC,IAAI,CAACG,OAAO,GAAG;QACf,IAAI,CAACF,MAAM,CAACH,GAAG,CAACC,KAAKC;QACrB,IAAI,CAACI,GAAG,CAACN,GAAG,CAACC,KAAKM,KAAKC,KAAK,CAACN;IAC/B;IAEAO,OAAOR,GAAM,EAAE;QACb,IAAI,IAAI,CAACK,GAAG,CAACI,GAAG,CAACT,MAAM;YACrB,IAAI,CAACI,OAAO,GAAG;YACf,IAAI,CAACF,MAAM,CAACM,MAAM,CAACR;YACnB,IAAI,CAACK,GAAG,CAACG,MAAM,CAACR;QAClB;IACF;IAEAG,IAAIH,GAAM,EAAE;QACV,OAAO,IAAI,CAACK,GAAG,CAACF,GAAG,CAACH;IACtB;IAEAU,YAAYC,oBAA0B,EAAE;QACtC,IAAIP,UAAU,IAAI,CAACA,OAAO;QAC1B,IAAIO,yBAAyBC,WAAW;YACtC,MAAMC,cAAcP,KAAKQ,SAAS,CAACH;YACnC,IAAI,IAAI,CAACA,oBAAoB,KAAKE,aAAa;gBAC7C,IAAI,CAACF,oBAAoB,GAAGE;gBAC5BT,UAAU;YACZ;QACF;QACA,IAAI,CAACA,OAAO,GAAG;QACf,OAAOA;IACT;IAEAW,SAAS;QACP,OAAO,IAAI,CAACV,GAAG,CAACU,MAAM;IACxB;IAEAC,UAAU;QACR,OAAO,IAAI,CAACX,GAAG,CAACW,OAAO;IACzB;;aA3CQd,SAAS,IAAIe;aACbZ,MAAM,IAAIY;aACVN,uBAA2CC;aAC3CR,UAAU;;AAyCpB;AAEO,MAAMhC;IA8BX8C,YAAY,EACV3C,OAAO,EACP4C,OAAO,EACPC,aAAa,EACbC,GAAG,EACHC,UAAU,EAOX,CAAE;aAzCKC,kBACN,IAAIzB;aACE0B,oBACN,IAAI1B;aACE2B,iBACN,IAAI3B;aACE4B,uBACN,IAAI5B;aACE6B,gBACN,IAAI7B;aACE8B,sBAGJ,IAAI9B;aACA+B,iBACN,IAAI/B;aACEgC,eACN,IAAIhC;QAEN,uDAAuD;QACvD,4EAA4E;aACpEiC,6BAAiDnB;aACjDoB,sBAAgC,EAAE;QAoBxC,IAAI,CAACzD,OAAO,GAAGA;QACf,IAAI,CAAC4C,OAAO,GAAGA;QACf,IAAI,CAACC,aAAa,GAAGA;QACrB,IAAI,CAACC,GAAG,GAAGA;QACX,IAAI,CAACC,UAAU,GAAGA;IACpB;IAEAd,OAAOR,GAAa,EAAE;QACpB,IAAI,CAACuB,eAAe,CAACf,MAAM,CAACR;QAC5B,IAAI,CAACwB,iBAAiB,CAAChB,MAAM,CAACR;QAC9B,IAAI,CAACyB,cAAc,CAACjB,MAAM,CAACR;QAC3B,IAAI,CAAC0B,oBAAoB,CAAClB,MAAM,CAACR;QACjC,IAAI,CAAC2B,aAAa,CAACnB,MAAM,CAACR;QAC1B,IAAI,CAAC4B,mBAAmB,CAACpB,MAAM,CAACR;QAChC,IAAI,CAAC6B,cAAc,CAACrB,MAAM,CAACR;IAC7B;IAEAiC,mBAAmBrC,QAAgB,EAAQ;QACzC,IAAI,CAAC2B,eAAe,CAACxB,GAAG,CACtBmC,IAAAA,qBAAW,EAAC,OAAO,UAAUtC,WAC7BD,2BACE,IAAI,CAACpB,OAAO,EACZ,GAAG4D,oCAAyB,CAAC,KAAK,CAAC,EACnCvC,UACA;IAGN;IAEQwC,qBAAqBC,SAAmC,EAAE;QAEhE,MAAMC,WAA2B;YAC/BC,MAAM,CAAC;YACPC,MAAM,CAAC;YACPpB,eAAe,IAAI,CAACA,aAAa;QACnC;QAEA,SAASqB,eACPC,aAA4B,EAC5BC,KAAoB;YAEpB,IAAK,MAAM3C,OAAO2C,MAAO;gBACvB,MAAMC,SAAUF,aAAa,CAAC1C,IAAI,KAAK;oBACrC6C,SAAS,CAAC;gBACZ;gBACAD,OAAOE,QAAQ,GAAGH,KAAK,CAAC3C,IAAI,CAAC8C,QAAQ;gBACrCF,OAAOG,YAAY,GAAGJ,KAAK,CAAC3C,IAAI,CAAC+C,YAAY;gBAC7CC,OAAOC,MAAM,CAACL,OAAOC,OAAO,EAAEF,KAAK,CAAC3C,IAAI,CAAC6C,OAAO;YAClD;QACF;QAEA,KAAK,MAAMK,KAAKb,UAAW;YACzBI,eAAeH,SAASC,IAAI,EAAEW,EAAEX,IAAI;YACpCE,eAAeH,SAASE,IAAI,EAAEU,EAAEV,IAAI;QACtC;QACA,IAAK,MAAMxC,OAAOsC,SAASC,IAAI,CAAE;YAC/B,MAAMY,QAAQb,SAASC,IAAI,CAACvC,IAAI;YAChCmD,MAAMN,OAAO,GAAGO,gBAAgBD,MAAMN,OAAO;QAC/C;QACA,IAAK,MAAM7C,OAAOsC,SAASE,IAAI,CAAE;YAC/B,MAAMW,QAAQb,SAASE,IAAI,CAACxC,IAAI;YAChCmD,MAAMN,OAAO,GAAGO,gBAAgBD,MAAMN,OAAO;QAC/C;QAEA,OAAOP;IACT;IAEQe,sBAA4B;QAClC,IAAI,CAAC,IAAI,CAAC9B,eAAe,CAACb,WAAW,IAAI;YACvC;QACF;QACA,MAAM4C,iBAAiB,IAAI,CAAClB,oBAAoB,CAC9C,IAAI,CAACb,eAAe,CAACR,MAAM;QAE7B,MAAMwC,yBAAyB1E,IAAAA,UAAI,EACjC,IAAI,CAACN,OAAO,EACZ,UACA,GAAG4D,oCAAyB,CAAC,KAAK,CAAC;QAErC,MAAMqB,uBAAuB3E,IAAAA,UAAI,EAC/B,IAAI,CAACN,OAAO,EACZ,UACA,GAAG4D,oCAAyB,CAAC,GAAG,CAAC;QAEnC,MAAMsB,OAAOnD,KAAKQ,SAAS,CAACwC,gBAAgB,MAAM;QAClD,IAAI,CAACtB,mBAAmB,CAAC0B,IAAI,CAACH;QAC9B,IAAI,CAACvB,mBAAmB,CAAC0B,IAAI,CAACF;QAC9BG,IAAAA,4BAAe,EAACJ,wBAAwBE;QACxCE,IAAAA,4BAAe,EACbH,sBACA,CAAC,2BAA2B,EAAElD,KAAKQ,SAAS,CAAC2C,OAAO;IAExD;IAEAG,qBAAqBhE,QAAgB,EAAQ;QAC3C,IAAI,CAAC4B,iBAAiB,CAACzB,GAAG,CACxBmC,IAAAA,qBAAW,EAAC,OAAO,UAAUtC,WAC7BD,2BACE,IAAI,CAACpB,OAAO,EACZsF,6BAAkB,EAClBjE,UACA;IAGN;IAEQkE,wBAA8B;QACpC,IAAI,CAAC,IAAI,CAACtC,iBAAiB,CAACd,WAAW,IAAI;YACzC;QACF;QACA,MAAMqD,mBAAmB,IAAI,CAACC,mBAAmB,CAC/C,IAAI,CAACxC,iBAAiB,CAACT,MAAM;QAE/B,MAAMkD,uBAAuBpF,IAAAA,UAAI,EAC/B,IAAI,CAACN,OAAO,EACZ,UACAsF,6BAAkB;QAEpB,IAAI,CAAC7B,mBAAmB,CAAC0B,IAAI,CAACO;QAC9BN,IAAAA,4BAAe,EACbM,sBACA3D,KAAKQ,SAAS,CAACiD,kBAAkB,MAAM;IAE3C;IAEQG,mBAAyB;QAC/B,IAAI,CAAC,IAAI,CAAC5C,UAAU,IAAI,CAAC,IAAI,CAACQ,YAAY,CAACpB,WAAW,IAAI;YACxD;QACF;QACA,MAAMyD,cAAc,IAAI,CAACC,iBAAiB,CAAC,IAAI,CAACtC,YAAY,CAACf,MAAM;QACnE,MAAMsD,WAAWxF,IAAAA,UAAI,EACnB,IAAI,CAACN,OAAO,EACZ,UACA,GAAG+F,yCAA8B,CAAC,KAAK,CAAC;QAE1C,MAAMC,SAAS1F,IAAAA,UAAI,EACjB,IAAI,CAACN,OAAO,EACZ,UACA,GAAG+F,yCAA8B,CAAC,GAAG,CAAC;QAExC,IAAI,CAACtC,mBAAmB,CAAC0B,IAAI,CAACW;QAC9B,IAAI,CAACrC,mBAAmB,CAAC0B,IAAI,CAACa;QAC9BZ,IAAAA,4BAAe,EAACU,UAAU/D,KAAKQ,SAAS,CAACqD,aAAa,MAAM;QAC5DR,IAAAA,4BAAe,EACbY,QACA,CAAC,sCAAsC,EAAEjE,KAAKQ,SAAS,CACrDR,KAAKQ,SAAS,CAACqD,eACd;IAEP;IAEAK,kBAAkB5E,QAAgB,EAAEnB,OAAwB,OAAO,EAAQ;QACzE,IAAI,CAACgD,cAAc,CAAC1B,GAAG,CACrBmC,IAAAA,qBAAW,EAACzD,MAAM,UAAUmB,WAC5BD,2BAA2B,IAAI,CAACpB,OAAO,EAAEkG,yBAAc,EAAE7E,UAAUnB;IAEvE;IAEAiG,wBACE9E,QAAgB,EAChBnB,OAAwB,OAAO,EACzB;QACN,IAAI,CAACiD,oBAAoB,CAAC3B,GAAG,CAC3BmC,IAAAA,qBAAW,EAACzD,MAAM,UAAUmB,WAC5BD,2BACE,IAAI,CAACpB,OAAO,EACZoG,0CAA+B,EAC/B/E,UACAnB;IAGN;IAEAmG,gBAAgBhF,QAAgB,EAAEnB,OAAwB,OAAO,EAAQ;QACvE,IAAI,CAAC,IAAI,CAAC6C,UAAU,EAAE;QACtB,IAAI,CAACQ,YAAY,CAAC/B,GAAG,CACnBmC,IAAAA,qBAAW,EAACzD,MAAM,UAAUmB,WAC5BD,2BACE,IAAI,CAACpB,OAAO,EACZ,GAAG+F,yCAA8B,CAAC,KAAK,CAAC,EACxC1E,UACAnB;IAGN;IAEQoG,oBACNxC,SAAkC,EAClCyC,gBAA0B,EAC1B;QACA,MAAMxC,WAAkE;YACtEyC,OAAO;gBACL,SAAS,EAAE;YACb;YACA,4EAA4E;YAC5EC,UAAU,EAAE;YACZC,eAAe,EAAE;YACjBH;YACAI,eAAe,EAAE;YACjBC,mBAAmB,CAAC;YACpBC,gCAAgC,CAAC;QACnC;QACA,KAAK,MAAMlC,KAAKb,UAAW;YACzBW,OAAOC,MAAM,CAACX,SAASyC,KAAK,EAAE7B,EAAE6B,KAAK;YACrC,IAAI7B,EAAEgC,aAAa,CAAC3F,MAAM,EAAE+C,SAAS4C,aAAa,GAAGhC,EAAEgC,aAAa;YACpE,2FAA2F;YAC3F,IAAIhC,EAAE+B,aAAa,CAAC1F,MAAM,EAAE+C,SAAS2C,aAAa,GAAG/B,EAAE+B,aAAa;YACpE,IAAI/B,EAAEiC,iBAAiB,EAAE;gBACvBnC,OAAOC,MAAM,CAACX,SAAS6C,iBAAiB,EAAGjC,EAAEiC,iBAAiB;YAChE;YACA,IAAIjC,EAAEkC,8BAA8B,EAAE;gBACpCpC,OAAOC,MAAM,CACXX,SAAS8C,8BAA8B,EACvClC,EAAEkC,8BAA8B;YAEpC;YACA,IAAIlC,EAAEmC,kBAAkB,EACtB/C,SAAS+C,kBAAkB,GAAGnC,EAAEmC,kBAAkB;QACtD;QACA/C,SAASyC,KAAK,GAAG3B,gBAAgBd,SAASyC,KAAK;QAC/C,OAAOzC;IACT;IAEQgD,0BACNjD,SAAwC,EACxCkD,QAAkC,EAClCC,cAAwB,EACH;QACrB,MAAMlD,WAAW;YACfmD,YAAYF;YACZG,aAAaF;QACf;QACA,KAAK,MAAMtC,KAAKb,UAAW;YACzBW,OAAOC,MAAM,CAACX,UAAUY;QAC1B;QACA,OAAOE,gBAAgBd;IACzB;IAEQqD,sCACNC,WAA2D,EAC3DC,kBAAwD,EAClD;QACN,MAAMN,WAAWM,sBAAsB;YACrC,GAAGD,WAAW;YACdE,aAAa,AAACF,CAAAA,aAAaE,eAAe,EAAE,AAAD,EAAGzF,GAAG,CAAC0F,sCAAY;YAC9DC,YAAY,AAACJ,CAAAA,aAAaI,cAAc,EAAE,AAAD,EAAG3F,GAAG,CAAC0F,sCAAY;YAC5DE,UAAU,AAACL,CAAAA,aAAaK,YAAY,EAAE,AAAD,EAAG5F,GAAG,CAAC0F,sCAAY;QAC1D;QAEA,MAAMG,uBAAuB5F,KAAKQ,SAAS,CACzCyE,SAASO,WAAW,CAACK,MAAM,CACzB,AACEC,QAAQ,8CACRC,0BAA0B;QAIhC,IAAI,IAAI,CAACtE,0BAA0B,KAAKmE,sBAAsB;YAC5D;QACF;QACA,IAAI,CAACnE,0BAA0B,GAAGmE;QAElC,MAAMI,kCAAkCzH,IAAAA,UAAI,EAC1C,IAAI,CAACN,OAAO,EACZ,UACA,GAAGgI,8CAAmC,CAAC,GAAG,CAAC;QAE7C,IAAI,CAACvE,mBAAmB,CAAC0B,IAAI,CAAC4C;QAE9B3C,IAAAA,4BAAe,EACb2C,iCACA,CAAC,2CAA2C,EAAEhG,KAAKQ,SAAS,CAC1DoF,sBACA,CAAC,CAAC;IAER;IAEQM,mBAAmB1B,gBAA0B,EAAQ;QAC3D,IAAI,CAAC,IAAI,CAACrD,cAAc,CAACf,WAAW,IAAI;YACtC;QACF;QACA,MAAM+F,gBAAgB,IAAI,CAAC5B,mBAAmB,CAC5C,IAAI,CAACpD,cAAc,CAACV,MAAM,IAC1B+D;QAGF,MAAM4B,oBAAoB7H,IAAAA,UAAI,EAAC,IAAI,CAACN,OAAO,EAAEkG,yBAAc;QAC3D,MAAMkC,8BAA8B9H,IAAAA,UAAI,EACtC,IAAI,CAACN,OAAO,EACZ,UACA,GAAGqI,oCAAyB,CAAC,GAAG,CAAC;QAGnC,IAAI,CAAC5E,mBAAmB,CAAC0B,IAAI,CAACgD;QAC9B,IAAI,CAAC1E,mBAAmB,CAAC0B,IAAI,CAACiD;QAC9BhD,IAAAA,4BAAe,EAAC+C,mBAAmBpG,KAAKQ,SAAS,CAAC2F,eAAe,MAAM;QACvE9C,IAAAA,4BAAe,EACbgD,6BACAE,IAAAA,mDAAyB,EAACJ;QAG5B,gCAAgC;QAChC,MAAMK,wBAAwB,IAAI,CAACjC,mBAAmB,CACpD;YACE,IAAI,CAACpD,cAAc,CAACtB,GAAG,CAAC+B,IAAAA,qBAAW,EAAC,SAAS,UAAU;YACvD,IAAI,CAACT,cAAc,CAACtB,GAAG,CAAC+B,IAAAA,qBAAW,EAAC,SAAS,UAAU;SACxD,CAACiE,MAAM,CAACY,UACTjC;QAEF,MAAMkC,4BAA4BnI,IAAAA,UAAI,EACpC,IAAI,CAACN,OAAO,EACZ,CAAC,SAAS,EAAEkG,yBAAc,EAAE;QAE9B,IAAI,CAACzC,mBAAmB,CAAC0B,IAAI,CAACsD;QAC9BrD,IAAAA,4BAAe,EACbqD,2BACA1G,KAAKQ,SAAS,CAACgG,uBAAuB,MAAM;IAEhD;IAEQG,yBACNC,WAAwB,EACxBtB,WAA2D,EAC3DC,kBAAwD,EAC9C;QACV,MAAMN,WAAW4B,IAAAA,2DAAiC,EAChDtB,sBAAsB;YACpB,GAAGD,WAAW;YACdE,aAAa,AAACF,CAAAA,aAAaE,eAAe,EAAE,AAAD,EAAGzF,GAAG,CAAC0F,sCAAY;YAC9DC,YAAY,AAACJ,CAAAA,aAAaI,cAAc,EAAE,AAAD,EAAG3F,GAAG,CAAC0F,sCAAY;YAC5DE,UAAU,AAACL,CAAAA,aAAaK,YAAY,EAAE,AAAD,EAAG5F,GAAG,CAAC0F,sCAAY;QAC1D;QAGF,MAAMqB,YAAY;eAAIF,YAAY5I,IAAI,CAAC+I,IAAI;SAAG;QAC9C,IAAIH,YAAYI,MAAM,CAACC,GAAG,EAAE;YAC1BH,UAAU1D,IAAI,CAAC;QACjB;QACA,IAAIwD,YAAYI,MAAM,CAACE,KAAK,EAAE;YAC5BJ,UAAU1D,IAAI,CAAC;QACjB;QAEA,MAAM8B,iBAAiBiC,IAAAA,sBAAe,EAACL;QAEvC,IAAIV,oBAAoB9H,WAAK,CAACC,IAAI,CAChC6I,mCAAwB,EACxB,IAAI,CAACvG,OAAO,EACZ;QAEF,IAAIwG,kBAAkB/I,WAAK,CAACC,IAAI,CAC9B6I,mCAAwB,EACxB,IAAI,CAACvG,OAAO,EACZ;QAGF,IACE,IAAI,CAACE,GAAG,IACR,CAAC,IAAI,CAACK,oBAAoB,CAAChB,WAAW,CAAC;YAAE6E;YAAUC;QAAe,IAClE;YACA,OAAO;gBAACkB;gBAAmBiB;aAAgB;QAC7C;QAEA,MAAMC,sBAAsB,IAAI,CAACtC,yBAAyB,CACxD,IAAI,CAAC5D,oBAAoB,CAACX,MAAM,IAChCwE,UACAC;QAGF,kFAAkF;QAClF,gFAAgF;QAChF,uCAAuC;QACvC,MAAMqC,sBAA+C,CAAC;QACtD,IAAIxC;QACJ,KAAK,MAAM,CAACrF,KAAKkD,EAAE,IAAI,IAAI,CAACzB,cAAc,CAACT,OAAO,GAAI;YACpD,sFAAsF;YACtF,wFAAwF;YACxF,gCAAgC;YAChC,IAAI8G,IAAAA,uBAAa,EAAC9H,KAAKvB,IAAI,KAAK,SAAS;YACzC,IAAIyE,EAAEmC,kBAAkB,EAAEA,qBAAqBnC,EAAEmC,kBAAkB;YACnE,KAAK,MAAM,CAAC0C,OAAOC,OAAO,IAAIhF,OAAOhC,OAAO,CAC1CkC,EAAEkC,8BAA8B,IAAI,CAAC,GACpC;gBACDyC,mBAAmB,CAACE,MAAM,GAAGC;YAC/B;QACF;QAEA,8FAA8F;QAC9F,YAAY;QACZ,MAAMC,qBAAqBjF,OAAOqE,IAAI,CAACQ,qBAAqBtI,MAAM,GAAG;QACrE,MAAM2I,wBACJ,CAAC,wBAAwB,EAAE5H,KAAKQ,SAAS,CAAC8G,qBAAqB,MAAM,GAAG,CAAC,CAAC,GACzEK,CAAAA,qBACG,CAAC,kCAAkC,EAAE3H,KAAKQ,SAAS,CAAC+G,qBAAqB,CAAC,CAAC,GAC1ExC,CAAAA,qBACG,CAAC,wCAAwC,EAAE/E,KAAKQ,SAAS,CACvDuE,oBACA,CAAC,CAAC,GACJ,EAAC,IACL,EAAC,IACL,CAAC,sDAAsD,CAAC;QAE1D1B,IAAAA,4BAAe,EACb9E,IAAAA,UAAI,EAAC,IAAI,CAACN,OAAO,EAAEmI,oBACnBwB;QAEF,0FAA0F;QAC1F,mCAAmC;QACnCvE,IAAAA,4BAAe,EAAC9E,IAAAA,UAAI,EAAC,IAAI,CAACN,OAAO,EAAEoJ,kBAAkBQ,6CAAmB;QAExE,OAAO;YAACzB;YAAmBiB;SAAgB;IAC7C;IAEAS,iBAAiBxI,QAAgB,EAAEnB,OAAwB,OAAO,EAAQ;QACxE,IAAI,CAACkD,aAAa,CAAC5B,GAAG,CACpBmC,IAAAA,qBAAW,EAACzD,MAAM,UAAUmB,WAC5BD,2BACE,IAAI,CAACpB,OAAO,EACZ,GAAG8J,6BAAkB,CAAC,KAAK,CAAC,EAC5BzI,UACAnB;IAGN;IAEQ6J,mBAAmBjG,SAAqC,EAAE;QAChE,MAAMC,WAA6B;YACjCiF,KAAK,CAAC;YACNgB,oBAAoB;YACpBxD,OAAO,CAAC;YACRyD,sBAAsB;QACxB;QACA,KAAK,MAAMtF,KAAKb,UAAW;YACzBW,OAAOC,MAAM,CAACX,SAASiF,GAAG,EAAErE,EAAEqE,GAAG;YACjCvE,OAAOC,MAAM,CAACX,SAASyC,KAAK,EAAE7B,EAAE6B,KAAK;YAErCzC,SAASiG,kBAAkB,GACzBjG,SAASiG,kBAAkB,IAAIrF,EAAEqF,kBAAkB;YACrDjG,SAASkG,oBAAoB,GAC3BlG,SAASkG,oBAAoB,IAAItF,EAAEsF,oBAAoB;QAC3D;QACAlG,SAASiF,GAAG,GAAGnE,gBAAgBd,SAASiF,GAAG;QAC3CjF,SAASyC,KAAK,GAAG3B,gBAAgBd,SAASyC,KAAK;QAC/C,OAAOzC;IACT;IAEA,MAAcmG,wBAAuC;QACnD,IAAI,CAAC,IAAI,CAAC9G,aAAa,CAACjB,WAAW,IAAI;YACrC;QACF;QACA,MAAMgI,eAAe,IAAI,CAACJ,kBAAkB,CAAC,IAAI,CAAC3G,aAAa,CAACZ,MAAM;QACtE,MAAM0C,OAAOnD,KAAKQ,SAAS,CAAC4H,cAAc,MAAM;QAEhD,MAAMC,uBAAuB9J,IAAAA,UAAI,EAC/B,IAAI,CAACN,OAAO,EACZ,UACA,GAAG8J,6BAAkB,CAAC,KAAK,CAAC;QAE9B,MAAMO,qBAAqB/J,IAAAA,UAAI,EAC7B,IAAI,CAACN,OAAO,EACZ,UACA,GAAG8J,6BAAkB,CAAC,GAAG,CAAC;QAE5B,IAAI,CAACrG,mBAAmB,CAAC0B,IAAI,CAACiF;QAC9B,IAAI,CAAC3G,mBAAmB,CAAC0B,IAAI,CAACkF;QAC9BjF,IAAAA,4BAAe,EAACgF,sBAAsBlF;QACtCE,IAAAA,4BAAe,EACbiF,oBACA,CAAC,0BAA0B,EAAEtI,KAAKQ,SAAS,CAAC2C,OAAO;IAEvD;IAEA;;GAEC,GACDoF,uBACEjJ,QAAgB,EAChBnB,IAAwD,EAC/C;QACT,MAAMqK,yBAAyBzK,gBAC7BuB,UACA,IAAI,CAACrB,OAAO,EACZwK,8BAAmB,EACnBtK,MACA;QAGF,uHAAuH;QACvH,IAAI,CAACQ,IAAAA,cAAU,EAAC6J,yBAAyB;YACvC,OAAO;QACT;QAEA,IAAI,CAAClH,mBAAmB,CAAC7B,GAAG,CAC1BmC,IAAAA,qBAAW,EACTzD,SAAS,gBAAgBA,SAAS,oBAAoB,SAASA,MAC/D,UACAmB,WAEFD,2BACE,IAAI,CAACpB,OAAO,EACZwK,8BAAmB,EACnBnJ,UACAnB;QAIJ,OAAO;IACT;IAEAuK,sBAAsBhJ,GAAa,EAAE;QACnC,OAAO,IAAI,CAAC4B,mBAAmB,CAACzB,GAAG,CAACH;IACtC;IAEAiJ,yBAAyBjJ,GAAa,EAAE;QACtC,OAAO,IAAI,CAAC4B,mBAAmB,CAACpB,MAAM,CAACR;IACzC;IAEQkJ,yBACN7G,SAAgD,EAC5B;QACpB,MAAMC,WAA+B;YACnC6G,SAAS;YACTC,YAAY,CAAC;YACbC,kBAAkB,EAAE;YACpBC,WAAW,CAAC;QACd;QACA,IAAIC,kBAAyD3I;QAC7D,KAAK,MAAMsC,KAAKb,UAAW;YACzBW,OAAOC,MAAM,CAACX,SAASgH,SAAS,EAAEpG,EAAEoG,SAAS;YAC7CtG,OAAOC,MAAM,CAACX,SAAS8G,UAAU,EAAElG,EAAEkG,UAAU;YAC/C,IAAIlG,EAAEqG,eAAe,EAAE;gBACrBA,kBAAkBrG,EAAEqG,eAAe;YACrC;QACF;QACAjH,SAASgH,SAAS,GAAGlG,gBAAgBd,SAASgH,SAAS;QACvDhH,SAAS8G,UAAU,GAAGhG,gBAAgBd,SAAS8G,UAAU;QACzD,MAAMI,2BAA2B,CAC/BC;YAEA,OAAO;gBACL,GAAGA,GAAG;gBACNC,OAAO;uBAAKH,iBAAiBG,SAAS,EAAE;uBAAMD,IAAIC,KAAK;iBAAC;YAC1D;QACF;QACA,KAAK,MAAM1J,OAAOgD,OAAOqE,IAAI,CAAC/E,SAAS8G,UAAU,EAAG;YAClD,MAAMnJ,QAAQqC,SAAS8G,UAAU,CAACpJ,IAAI;YACtCsC,SAAS8G,UAAU,CAACpJ,IAAI,GAAGwJ,yBAAyBvJ;QACtD;QACA,KAAK,MAAMD,OAAOgD,OAAOqE,IAAI,CAAC/E,SAASgH,SAAS,EAAG;YACjD,MAAMrJ,QAAQqC,SAASgH,SAAS,CAACtJ,IAAI;YACrCsC,SAASgH,SAAS,CAACtJ,IAAI,GAAGwJ,yBAAyBvJ;QACrD;QACA,KAAK,MAAMwJ,OAAOzG,OAAOjC,MAAM,CAACuB,SAASgH,SAAS,EAAEK,MAAM,CACxD3G,OAAOjC,MAAM,CAACuB,SAAS8G,UAAU,GAChC;YACD,KAAK,MAAMQ,WAAWH,IAAII,QAAQ,CAAE;gBAClC,IAAI,CAACD,QAAQE,MAAM,EAAE;oBACnBF,QAAQE,MAAM,GAAGC,IAAAA,iCAAgB,EAACH,QAAQI,cAAc,EAAE,EAAE,EAAE;wBAC5DC,WAAW;wBACXC,WAAW;wBACXC,QAAQ;oBACV,GAAGC,MAAM,CAACC,UAAU,CAAC,OAAO;gBAC9B;YACF;QACF;QACA/H,SAAS+G,gBAAgB,GAAGrG,OAAOqE,IAAI,CAAC/E,SAAS8G,UAAU;QAE3D,OAAO9G;IACT;IAEQgI,0BAEN;QACA,IAAIC,+BAA+B3L,WAAK,CAACC,IAAI,CAC3C6I,mCAAwB,EACxB,IAAI,CAACvG,OAAO,EACZqJ,+CAAoC;QAGtC,IAAI,IAAI,CAACnJ,GAAG,IAAI,CAAC,IAAI,CAACO,mBAAmB,CAAClB,WAAW,IAAI;YACvD,OAAO;gBACL6J;YACF;QACF;QACA,MAAME,qBAAqB,IAAI,CAACvB,wBAAwB,CACtD,IAAI,CAACtH,mBAAmB,CAACb,MAAM;QAGjC,6BAA6B;QAE7B,8CAA8C;QAC9C,IAAK,MAAMf,OAAOyK,mBAAmBrB,UAAU,CAAE;YAC/CqB,mBAAmBrB,UAAU,CAACpJ,IAAI,CAAC6J,QAAQ,CAACa,OAAO,CAAC,CAACd;gBACnD,IAAI,CAACA,QAAQE,MAAM,CAACa,UAAU,CAAC,MAAM;oBACnC,MAAMC,aAAaC,IAAAA,8BAAc,EAACjB,QAAQE,MAAM;oBAChD,IAAIc,WAAWpD,KAAK,IAAI,CAACoD,WAAWE,QAAQ,EAAE;wBAC5C,MAAM,IAAIC,MAAM,CAAC,gBAAgB,EAAEnB,QAAQE,MAAM,EAAE;oBACrD;oBACAF,QAAQE,MAAM,GAAGc,WAAWE,QAAQ;gBACtC;YACF;QACF;QAEA,MAAMhC,yBAAyBjK,IAAAA,UAAI,EACjC,IAAI,CAACN,OAAO,EACZ,UACAwK,8BAAmB;QAErB,IAAI,CAAC/G,mBAAmB,CAAC0B,IAAI,CAACoF;QAC9BnF,IAAAA,4BAAe,EACbmF,wBACAxI,KAAKQ,SAAS,CAAC2J,oBAAoB,MAAM;QAG3C,+FAA+F;QAC/F,wCAAwC;QACxC,MAAMZ,WAAWY,oBAAoBrB,UAAU,CAAC,IAAI,EAAES,YAAY,EAAE;QAEpE,MAAMmB,6BAA6B,CAAC,6BAA6B,EAAE1K,KAAKQ,SAAS,CAC/E+I,UACA,MACA,GACA,iEAAiE,CAAC;QAEpE,IAAI,CAAC7H,mBAAmB,CAAC0B,IAAI,CAAC6G;QAC9B5G,IAAAA,4BAAe,EACb9E,IAAAA,UAAI,EAAC,IAAI,CAACN,OAAO,EAAEgM,+BACnBS;QAGF,OAAO;YACLT;QACF;IACF;IAEAU,kBAAkBrL,QAAgB,EAAQ;QACxC,IAAI,CAACiC,cAAc,CAAC9B,GAAG,CACrBmC,IAAAA,qBAAW,EAAC,SAAS,UAAUtC,WAC/BD,2BAA2B,IAAI,CAACpB,OAAO,EAAE2M,yBAAc,EAAEtL;IAE7D;IAEQoE,oBAAoB3B,SAAkC,EAAE;QAC9D,MAAMC,WAA0B,CAAC;QACjC,KAAK,MAAMY,KAAKb,UAAW;YACzBW,OAAOC,MAAM,CAACX,UAAUY;QAC1B;QACA,OAAOE,gBAAgBd;IACzB;IAEQ8B,kBAAkB/B,SAAiD,EAAE;QAC3E,MAAMC,WAAyC,CAAC;QAChD,KAAK,MAAMY,KAAKb,UAAW;YACzBW,OAAOC,MAAM,CAACX,UAAUY;QAC1B;QACA,OAAOE,gBAAgBd;IACzB;IAEQ6I,qBAA2B;QACjC,IAAI,CAAC,IAAI,CAACtJ,cAAc,CAACnB,WAAW,IAAI;YACtC;QACF;QACA,MAAM0K,gBAAgB,IAAI,CAACpH,mBAAmB,CAAC,IAAI,CAACnC,cAAc,CAACd,MAAM;QACzE,MAAMsK,oBAAoBxM,IAAAA,UAAI,EAAC,IAAI,CAACN,OAAO,EAAE,UAAU2M,yBAAc;QACrE,IAAI,CAAClJ,mBAAmB,CAAC0B,IAAI,CAAC2H;QAC9B1H,IAAAA,4BAAe,EAAC0H,mBAAmB/K,KAAKQ,SAAS,CAACsK,eAAe,MAAM;IACzE;IAEAE,eAAe,EACb1F,WAAW,EACXC,kBAAkB,EAClBqB,WAAW,EAKZ,EAAQ;QACP,IAAI,CAAC7D,mBAAmB;QACxB,IAAI,CAACS,qBAAqB;QAC1B,MAAMgB,mBAAmB,IAAI,CAACmC,wBAAwB,CACpDC,aACAtB,aACAC;QAEF,MAAM,EAAE0E,4BAA4B,EAAE,GAAG,IAAI,CAACD,uBAAuB;QACrE,IAAI,CAAC9D,kBAAkB,CAAC;eAAI1B;YAAkByF;SAA6B;QAC3E,IAAI,CAAC5E,qCAAqC,CAACC,aAAaC;QACxD,IAAI,CAAC4C,qBAAqB;QAC1B,IAAI,CAAC0C,kBAAkB;QAEvB,IAAI,CAACjH,gBAAgB;QAErB,kEAAkE;QAClE,IAAI,IAAI,CAAClC,mBAAmB,CAACzC,MAAM,GAAG,GAAG;YACvCgM,IAAAA,yBAAW,EAAC,IAAI,CAACvJ,mBAAmB;YACpC,IAAI,CAACA,mBAAmB,GAAG,EAAE;QAC/B;IACF;AACF;AAEA,SAASoB,gBAAgBoI,GAAwB;IAC/C,OAAOxI,OAAOqE,IAAI,CAACmE,KAChBC,IAAI,GACJC,MAAM,CACL,CAACC,KAAK3L;QACJ2L,GAAG,CAAC3L,IAAI,GAAGwL,GAAG,CAACxL,IAAI;QACnB,OAAO2L;IACT,GACA,CAAC;AAEP","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.d.ts b/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56ab6bb4d1597ebe7f25dc0fe3ba5aab9ce919cf --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.d.ts @@ -0,0 +1,26 @@ +import type { Issue, StyledString, TurbopackResult } from '../../../build/swc/types'; +import type { EntryKey } from './entry-key'; +import type { NextConfigComplete } from '../../../server/config-shared'; +type IssueKey = `${Issue['severity']}-${Issue['filePath']}-${string}-${string}`; +export type IssuesMap = Map; +export type EntryIssuesMap = Map; +export type TopLevelIssuesMap = IssuesMap; +/** + * An error generated from emitted Turbopack issues. This can include build + * errors caused by issues with user code. + */ +export declare class ModuleBuildError extends Error { + name: string; +} +/** + * Thin stopgap workaround layer to mimic existing wellknown-errors-plugin in webpack's build + * to emit certain type of errors into cli. + */ +export declare function isWellKnownError(issue: Issue): boolean; +export declare function getIssueKey(issue: Issue): IssueKey; +export declare function processIssues(currentEntryIssues: EntryIssuesMap, key: EntryKey, result: TurbopackResult, throwIssue: boolean, logErrors: boolean): void; +export declare function formatIssue(issue: Issue): string; +export declare function isRelevantWarning(issue: Issue): boolean; +export declare function renderStyledStringToErrorAnsi(string: StyledString): string; +export declare function isFileSystemCacheEnabledForDev(config: NextConfigComplete): boolean; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.js b/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..9c85f56754d2c56e51b893fc1600efd511f59341 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.js @@ -0,0 +1,266 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ModuleBuildError: null, + formatIssue: null, + getIssueKey: null, + isFileSystemCacheEnabledForDev: null, + isRelevantWarning: null, + isWellKnownError: null, + processIssues: null, + renderStyledStringToErrorAnsi: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ModuleBuildError: function() { + return ModuleBuildError; + }, + formatIssue: function() { + return formatIssue; + }, + getIssueKey: function() { + return getIssueKey; + }, + isFileSystemCacheEnabledForDev: function() { + return isFileSystemCacheEnabledForDev; + }, + isRelevantWarning: function() { + return isRelevantWarning; + }, + isWellKnownError: function() { + return isWellKnownError; + }, + processIssues: function() { + return processIssues; + }, + renderStyledStringToErrorAnsi: function() { + return renderStyledStringToErrorAnsi; + } +}); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _picocolors = require("../../../lib/picocolors"); +const _magicidentifier = require("../magic-identifier"); +const _log = /*#__PURE__*/ _interop_require_wildcard._(require("../../../build/output/log")); +const VERBOSE_ISSUES = !!process.env.NEXT_TURBOPACK_VERBOSE_ISSUES; +class ModuleBuildError extends Error { + constructor(...args){ + super(...args), this.name = 'ModuleBuildError'; + } +} +function isWellKnownError(issue) { + const { title } = issue; + const formattedTitle = renderStyledStringToErrorAnsi(title); + // TODO: add more well known errors + if (formattedTitle.includes('Module not found') || formattedTitle.includes('Unknown module type')) { + return true; + } + return false; +} +function getIssueKey(issue) { + return `${issue.severity}-${issue.filePath}-${JSON.stringify(issue.title)}-${JSON.stringify(issue.description)}`; +} +function processIssues(currentEntryIssues, key, result, throwIssue, logErrors) { + const newIssues = new Map(); + currentEntryIssues.set(key, newIssues); + const relevantIssues = new Set(); + for (const issue of result.issues){ + if (issue.severity !== 'error' && issue.severity !== 'fatal' && issue.severity !== 'warning') continue; + const issueKey = getIssueKey(issue); + newIssues.set(issueKey, issue); + if (issue.severity !== 'warning') { + if (throwIssue) { + const formatted = formatIssue(issue); + relevantIssues.add(formatted); + } else if (logErrors && isWellKnownError(issue)) { + const formatted = formatIssue(issue); + _log.error(formatted); + } + } + } + if (relevantIssues.size && throwIssue) { + throw new ModuleBuildError([ + ...relevantIssues + ].join('\n\n')); + } +} +function formatFilePath(filePath) { + return filePath.replace('[project]/', './').replaceAll('/./', '/').replace('\\\\?\\', ''); +} +function formatIssue(issue) { + const { filePath, title, description, detail, source, importTraces, severity } = issue; + let { documentationLink } = issue; + let formattedTitle = renderStyledStringToErrorAnsi(title).replace(/\n/g, '\n '); + if (severity === 'bug' || severity === 'error' || severity === 'fatal') { + formattedTitle = (0, _picocolors.bold)(`${(0, _picocolors.red)('Error')}: ${formattedTitle}`); + } else if (severity === 'warning') { + formattedTitle = (0, _picocolors.bold)(`${(0, _picocolors.yellow)('Warning')}: ${formattedTitle}`); + } else { + formattedTitle = (0, _picocolors.bold)(`Info: ${formattedTitle}`); + } + // TODO: Use error codes to identify these + // TODO: Generalize adapting Turbopack errors to Next.js errors + if (formattedTitle.includes('Module not found')) { + // For compatiblity with webpack + // TODO: include columns in webpack errors. + documentationLink = 'https://nextjs.org/docs/messages/module-not-found'; + } + const formattedFilePath = formatFilePath(filePath); + let message = ''; + if (source?.range) { + const { start } = source.range; + message = `${formattedFilePath}:${start.line + 1}:${start.column + 1}\n${formattedTitle}`; + } else if (formattedFilePath) { + message = `${formattedFilePath}\n${formattedTitle}`; + } else { + message = formattedTitle; + } + message += '\n'; + if (issue.codeFrame) { + message += issue.codeFrame.trimEnd() + '\n\n'; + } + if (description) { + if (description.type === 'text' && description.value.includes(`Cannot find module 'sass'`)) { + message += "To use Next.js' built-in Sass support, you first need to install `sass`.\n"; + message += 'Run `npm i sass` or `yarn add sass` inside your workspace.\n'; + message += '\nLearn more: https://nextjs.org/docs/messages/install-sass\n'; + } else { + message += renderStyledStringToErrorAnsi(description) + '\n\n'; + } + } + // TODO: make it easier to enable this for debugging + if (VERBOSE_ISSUES && detail) { + message += renderStyledStringToErrorAnsi(detail) + '\n\n'; + } + // Render additional sources (e.g., generated code from a loader) + for (const additional of issue.additionalSources ?? []){ + if (additional.codeFrame) { + const additionalFilePath = formatFilePath(additional.source.source.filePath); + const loc = additional.source.range ? `:${additional.source.range.start.line + 1}:${additional.source.range.start.column + 1}` : ''; + message += `${additional.description}:\n${additionalFilePath}${loc}\n${additional.codeFrame.trimEnd()}\n\n`; + } + } + if (importTraces?.length) { + // This is the same logic as in turbopack/crates/turbopack-cli-utils/src/issue.rs + // We end up with multiple traces when the file with the error is reachable from multiple + // different entry points (e.g. ssr, client) + message += `Import trace${importTraces.length > 1 ? 's' : ''}:\n`; + const everyTraceHasADistinctRootLayer = new Set(importTraces.map(leafLayerName).filter((l)=>l != null)).size === importTraces.length; + for(let i = 0; i < importTraces.length; i++){ + const trace = importTraces[i]; + const layer = leafLayerName(trace); + let traceIndent = ' '; + // If this is true, layer must be present + if (everyTraceHasADistinctRootLayer) { + message += ` ${layer}:\n`; + } else { + if (importTraces.length > 1) { + // Otherwise use simple 1 based indices to disambiguate + message += ` #${i + 1}`; + if (layer) { + message += ` [${layer}]`; + } + message += ':\n'; + } else if (layer) { + message += ` [${layer}]:\n`; + } else { + // If there is a single trace and no layer name just don't indent it. + traceIndent = ' '; + } + } + message += formatIssueTrace(trace, traceIndent, !identicalLayers(trace)); + } + } + if (documentationLink) { + message += documentationLink + '\n\n'; + } + return message; +} +/** Returns the first present layer name in the trace */ function leafLayerName(items) { + for (const item of items){ + const layer = item.layer; + if (layer != null) return layer; + } + return undefined; +} +/** + * Returns whether or not all items share the same layer. + * If a layer is absent we ignore it in this analysis + */ function identicalLayers(items) { + const firstPresentLayer = items.findIndex((t)=>t.layer != null); + if (firstPresentLayer === -1) return true // all layers are absent + ; + const layer = items[firstPresentLayer].layer; + for(let i = firstPresentLayer + 1; i < items.length; i++){ + const itemLayer = items[i].layer; + if (itemLayer == null || itemLayer !== layer) { + return false; + } + } + return true; +} +function formatIssueTrace(items, indent, printLayers) { + return `${items.map((item)=>{ + let r = indent; + if (item.fsName !== 'project') { + r += `[${item.fsName}]/`; + } else { + // This is consistent with webpack's output + r += './'; + } + r += item.path; + if (printLayers && item.layer) { + r += ` [${item.layer}]`; + } + return r; + }).join('\n')}\n\n`; +} +function isRelevantWarning(issue) { + return issue.severity === 'warning' && !isNodeModulesIssue(issue); +} +function isNodeModulesIssue(issue) { + if (issue.severity === 'warning' && issue.stage === 'config') { + // Override for the externalize issue + // `Package foo (serverExternalPackages or default list) can't be external` + if (renderStyledStringToErrorAnsi(issue.title).includes("can't be external")) { + return false; + } + } + return issue.severity === 'warning' && (issue.filePath.match(/^(?:.*[\\/])?node_modules(?:[\\/].*)?$/) !== null || // Ignore Next.js itself when running next directly in the monorepo where it is not inside + // node_modules anyway. + // TODO(mischnic) prevent matches when this is published to npm + issue.filePath.startsWith('[project]/packages/next/')); +} +function renderStyledStringToErrorAnsi(string) { + function applyDeobfuscation(str) { + // Use shared deobfuscate function and apply magenta color to identifiers + const deobfuscated = (0, _magicidentifier.deobfuscateText)(str); + // Color any {...} wrapped identifiers with magenta + return deobfuscated.replace(/\{([^}]+)\}/g, (match)=>(0, _picocolors.magenta)(match)); + } + switch(string.type){ + case 'text': + return applyDeobfuscation(string.value); + case 'strong': + return (0, _picocolors.bold)((0, _picocolors.red)(applyDeobfuscation(string.value))); + case 'code': + return (0, _picocolors.green)(applyDeobfuscation(string.value)); + case 'line': + return string.value.map(renderStyledStringToErrorAnsi).join(''); + case 'stack': + return string.value.map(renderStyledStringToErrorAnsi).join('\n'); + default: + throw new Error('Unknown StyledString type', string); + } +} +function isFileSystemCacheEnabledForDev(config) { + return config.experimental?.turbopackFileSystemCacheForDev || false; +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.js.map b/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..32025df1f93acdbb05d9776431bbb8d14de030a1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/turbopack/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/turbopack/utils.ts"],"sourcesContent":["import type {\n Issue,\n PlainTraceItem,\n StyledString,\n TurbopackResult,\n} from '../../../build/swc/types'\n\nimport { bold, green, magenta, red, yellow } from '../../../lib/picocolors'\nimport { deobfuscateText } from '../magic-identifier'\nimport type { EntryKey } from './entry-key'\nimport * as Log from '../../../build/output/log'\nimport type { NextConfigComplete } from '../../../server/config-shared'\n\ntype IssueKey = `${Issue['severity']}-${Issue['filePath']}-${string}-${string}`\nexport type IssuesMap = Map\nexport type EntryIssuesMap = Map\nexport type TopLevelIssuesMap = IssuesMap\n\nconst VERBOSE_ISSUES = !!process.env.NEXT_TURBOPACK_VERBOSE_ISSUES\n\n/**\n * An error generated from emitted Turbopack issues. This can include build\n * errors caused by issues with user code.\n */\nexport class ModuleBuildError extends Error {\n name = 'ModuleBuildError'\n}\n\n/**\n * Thin stopgap workaround layer to mimic existing wellknown-errors-plugin in webpack's build\n * to emit certain type of errors into cli.\n */\nexport function isWellKnownError(issue: Issue): boolean {\n const { title } = issue\n const formattedTitle = renderStyledStringToErrorAnsi(title)\n // TODO: add more well known errors\n if (\n formattedTitle.includes('Module not found') ||\n formattedTitle.includes('Unknown module type')\n ) {\n return true\n }\n\n return false\n}\n\nexport function getIssueKey(issue: Issue): IssueKey {\n return `${issue.severity}-${issue.filePath}-${JSON.stringify(\n issue.title\n )}-${JSON.stringify(issue.description)}`\n}\n\nexport function processIssues(\n currentEntryIssues: EntryIssuesMap,\n key: EntryKey,\n result: TurbopackResult,\n throwIssue: boolean,\n logErrors: boolean\n) {\n const newIssues = new Map()\n currentEntryIssues.set(key, newIssues)\n\n const relevantIssues = new Set()\n\n for (const issue of result.issues) {\n if (\n issue.severity !== 'error' &&\n issue.severity !== 'fatal' &&\n issue.severity !== 'warning'\n )\n continue\n\n const issueKey = getIssueKey(issue)\n newIssues.set(issueKey, issue)\n\n if (issue.severity !== 'warning') {\n if (throwIssue) {\n const formatted = formatIssue(issue)\n relevantIssues.add(formatted)\n }\n // if we throw the issue it will most likely get handed and logged elsewhere\n else if (logErrors && isWellKnownError(issue)) {\n const formatted = formatIssue(issue)\n Log.error(formatted)\n }\n }\n }\n\n if (relevantIssues.size && throwIssue) {\n throw new ModuleBuildError([...relevantIssues].join('\\n\\n'))\n }\n}\n\nfunction formatFilePath(filePath: string): string {\n return filePath\n .replace('[project]/', './')\n .replaceAll('/./', '/')\n .replace('\\\\\\\\?\\\\', '')\n}\n\nexport function formatIssue(issue: Issue) {\n const {\n filePath,\n title,\n description,\n detail,\n source,\n importTraces,\n severity,\n } = issue\n let { documentationLink } = issue\n let formattedTitle = renderStyledStringToErrorAnsi(title).replace(\n /\\n/g,\n '\\n '\n )\n\n if (severity === 'bug' || severity === 'error' || severity === 'fatal') {\n formattedTitle = bold(`${red('Error')}: ${formattedTitle}`)\n } else if (severity === 'warning') {\n formattedTitle = bold(`${yellow('Warning')}: ${formattedTitle}`)\n } else {\n formattedTitle = bold(`Info: ${formattedTitle}`)\n }\n\n // TODO: Use error codes to identify these\n // TODO: Generalize adapting Turbopack errors to Next.js errors\n if (formattedTitle.includes('Module not found')) {\n // For compatiblity with webpack\n // TODO: include columns in webpack errors.\n documentationLink = 'https://nextjs.org/docs/messages/module-not-found'\n }\n\n const formattedFilePath = formatFilePath(filePath)\n\n let message = ''\n\n if (source?.range) {\n const { start } = source.range\n message = `${formattedFilePath}:${start.line + 1}:${\n start.column + 1\n }\\n${formattedTitle}`\n } else if (formattedFilePath) {\n message = `${formattedFilePath}\\n${formattedTitle}`\n } else {\n message = formattedTitle\n }\n message += '\\n'\n\n if (issue.codeFrame) {\n message += issue.codeFrame.trimEnd() + '\\n\\n'\n }\n\n if (description) {\n if (\n description.type === 'text' &&\n description.value.includes(`Cannot find module 'sass'`)\n ) {\n message +=\n \"To use Next.js' built-in Sass support, you first need to install `sass`.\\n\"\n message += 'Run `npm i sass` or `yarn add sass` inside your workspace.\\n'\n message += '\\nLearn more: https://nextjs.org/docs/messages/install-sass\\n'\n } else {\n message += renderStyledStringToErrorAnsi(description) + '\\n\\n'\n }\n }\n\n // TODO: make it easier to enable this for debugging\n if (VERBOSE_ISSUES && detail) {\n message += renderStyledStringToErrorAnsi(detail) + '\\n\\n'\n }\n\n // Render additional sources (e.g., generated code from a loader)\n for (const additional of issue.additionalSources ?? []) {\n if (additional.codeFrame) {\n const additionalFilePath = formatFilePath(\n additional.source.source.filePath\n )\n const loc = additional.source.range\n ? `:${additional.source.range.start.line + 1}:${additional.source.range.start.column + 1}`\n : ''\n message += `${additional.description}:\\n${additionalFilePath}${loc}\\n${additional.codeFrame.trimEnd()}\\n\\n`\n }\n }\n\n if (importTraces?.length) {\n // This is the same logic as in turbopack/crates/turbopack-cli-utils/src/issue.rs\n // We end up with multiple traces when the file with the error is reachable from multiple\n // different entry points (e.g. ssr, client)\n message += `Import trace${importTraces.length > 1 ? 's' : ''}:\\n`\n const everyTraceHasADistinctRootLayer =\n new Set(importTraces.map(leafLayerName).filter((l) => l != null)).size ===\n importTraces.length\n for (let i = 0; i < importTraces.length; i++) {\n const trace = importTraces[i]\n const layer = leafLayerName(trace)\n let traceIndent = ' '\n // If this is true, layer must be present\n if (everyTraceHasADistinctRootLayer) {\n message += ` ${layer}:\\n`\n } else {\n if (importTraces.length > 1) {\n // Otherwise use simple 1 based indices to disambiguate\n message += ` #${i + 1}`\n if (layer) {\n message += ` [${layer}]`\n }\n message += ':\\n'\n } else if (layer) {\n message += ` [${layer}]:\\n`\n } else {\n // If there is a single trace and no layer name just don't indent it.\n traceIndent = ' '\n }\n }\n message += formatIssueTrace(trace, traceIndent, !identicalLayers(trace))\n }\n }\n if (documentationLink) {\n message += documentationLink + '\\n\\n'\n }\n return message\n}\n\n/** Returns the first present layer name in the trace */\nfunction leafLayerName(items: PlainTraceItem[]): string | undefined {\n for (const item of items) {\n const layer = item.layer\n if (layer != null) return layer\n }\n return undefined\n}\n\n/**\n * Returns whether or not all items share the same layer.\n * If a layer is absent we ignore it in this analysis\n */\nfunction identicalLayers(items: PlainTraceItem[]): boolean {\n const firstPresentLayer = items.findIndex((t) => t.layer != null)\n if (firstPresentLayer === -1) return true // all layers are absent\n const layer = items[firstPresentLayer].layer\n for (let i = firstPresentLayer + 1; i < items.length; i++) {\n const itemLayer = items[i].layer\n if (itemLayer == null || itemLayer !== layer) {\n return false\n }\n }\n return true\n}\n\nfunction formatIssueTrace(\n items: PlainTraceItem[],\n indent: string,\n printLayers: boolean\n): string {\n return `${items\n .map((item) => {\n let r = indent\n if (item.fsName !== 'project') {\n r += `[${item.fsName}]/`\n } else {\n // This is consistent with webpack's output\n r += './'\n }\n r += item.path\n if (printLayers && item.layer) {\n r += ` [${item.layer}]`\n }\n return r\n })\n .join('\\n')}\\n\\n`\n}\n\nexport function isRelevantWarning(issue: Issue): boolean {\n return issue.severity === 'warning' && !isNodeModulesIssue(issue)\n}\n\nfunction isNodeModulesIssue(issue: Issue): boolean {\n if (issue.severity === 'warning' && issue.stage === 'config') {\n // Override for the externalize issue\n // `Package foo (serverExternalPackages or default list) can't be external`\n if (\n renderStyledStringToErrorAnsi(issue.title).includes(\"can't be external\")\n ) {\n return false\n }\n }\n\n return (\n issue.severity === 'warning' &&\n (issue.filePath.match(/^(?:.*[\\\\/])?node_modules(?:[\\\\/].*)?$/) !== null ||\n // Ignore Next.js itself when running next directly in the monorepo where it is not inside\n // node_modules anyway.\n // TODO(mischnic) prevent matches when this is published to npm\n issue.filePath.startsWith('[project]/packages/next/'))\n )\n}\n\nexport function renderStyledStringToErrorAnsi(string: StyledString): string {\n function applyDeobfuscation(str: string): string {\n // Use shared deobfuscate function and apply magenta color to identifiers\n const deobfuscated = deobfuscateText(str)\n // Color any {...} wrapped identifiers with magenta\n return deobfuscated.replace(/\\{([^}]+)\\}/g, (match) => magenta(match))\n }\n\n switch (string.type) {\n case 'text':\n return applyDeobfuscation(string.value)\n case 'strong':\n return bold(red(applyDeobfuscation(string.value)))\n case 'code':\n return green(applyDeobfuscation(string.value))\n case 'line':\n return string.value.map(renderStyledStringToErrorAnsi).join('')\n case 'stack':\n return string.value.map(renderStyledStringToErrorAnsi).join('\\n')\n default:\n throw new Error('Unknown StyledString type', string)\n }\n}\n\nexport function isFileSystemCacheEnabledForDev(\n config: NextConfigComplete\n): boolean {\n return config.experimental?.turbopackFileSystemCacheForDev || false\n}\n"],"names":["ModuleBuildError","formatIssue","getIssueKey","isFileSystemCacheEnabledForDev","isRelevantWarning","isWellKnownError","processIssues","renderStyledStringToErrorAnsi","VERBOSE_ISSUES","process","env","NEXT_TURBOPACK_VERBOSE_ISSUES","Error","name","issue","title","formattedTitle","includes","severity","filePath","JSON","stringify","description","currentEntryIssues","key","result","throwIssue","logErrors","newIssues","Map","set","relevantIssues","Set","issues","issueKey","formatted","add","Log","error","size","join","formatFilePath","replace","replaceAll","detail","source","importTraces","documentationLink","bold","red","yellow","formattedFilePath","message","range","start","line","column","codeFrame","trimEnd","type","value","additional","additionalSources","additionalFilePath","loc","length","everyTraceHasADistinctRootLayer","map","leafLayerName","filter","l","i","trace","layer","traceIndent","formatIssueTrace","identicalLayers","items","item","undefined","firstPresentLayer","findIndex","t","itemLayer","indent","printLayers","r","fsName","path","isNodeModulesIssue","stage","match","startsWith","string","applyDeobfuscation","str","deobfuscated","deobfuscateText","magenta","green","config","experimental","turbopackFileSystemCacheForDev"],"mappings":";;;;;;;;;;;;;;;;;;;;;IAwBaA,gBAAgB;eAAhBA;;IA4EGC,WAAW;eAAXA;;IAtDAC,WAAW;eAAXA;;IAmRAC,8BAA8B;eAA9BA;;IAjDAC,iBAAiB;eAAjBA;;IAhPAC,gBAAgB;eAAhBA;;IAoBAC,aAAa;eAAbA;;IAqPAC,6BAA6B;eAA7BA;;;;4BAlSkC;iCAClB;+DAEX;AAQrB,MAAMC,iBAAiB,CAAC,CAACC,QAAQC,GAAG,CAACC,6BAA6B;AAM3D,MAAMX,yBAAyBY;;QAA/B,qBACLC,OAAO;;AACT;AAMO,SAASR,iBAAiBS,KAAY;IAC3C,MAAM,EAAEC,KAAK,EAAE,GAAGD;IAClB,MAAME,iBAAiBT,8BAA8BQ;IACrD,mCAAmC;IACnC,IACEC,eAAeC,QAAQ,CAAC,uBACxBD,eAAeC,QAAQ,CAAC,wBACxB;QACA,OAAO;IACT;IAEA,OAAO;AACT;AAEO,SAASf,YAAYY,KAAY;IACtC,OAAO,GAAGA,MAAMI,QAAQ,CAAC,CAAC,EAAEJ,MAAMK,QAAQ,CAAC,CAAC,EAAEC,KAAKC,SAAS,CAC1DP,MAAMC,KAAK,EACX,CAAC,EAAEK,KAAKC,SAAS,CAACP,MAAMQ,WAAW,GAAG;AAC1C;AAEO,SAAShB,cACdiB,kBAAkC,EAClCC,GAAa,EACbC,MAA0B,EAC1BC,UAAmB,EACnBC,SAAkB;IAElB,MAAMC,YAAY,IAAIC;IACtBN,mBAAmBO,GAAG,CAACN,KAAKI;IAE5B,MAAMG,iBAAiB,IAAIC;IAE3B,KAAK,MAAMlB,SAASW,OAAOQ,MAAM,CAAE;QACjC,IACEnB,MAAMI,QAAQ,KAAK,WACnBJ,MAAMI,QAAQ,KAAK,WACnBJ,MAAMI,QAAQ,KAAK,WAEnB;QAEF,MAAMgB,WAAWhC,YAAYY;QAC7Bc,UAAUE,GAAG,CAACI,UAAUpB;QAExB,IAAIA,MAAMI,QAAQ,KAAK,WAAW;YAChC,IAAIQ,YAAY;gBACd,MAAMS,YAAYlC,YAAYa;gBAC9BiB,eAAeK,GAAG,CAACD;YACrB,OAEK,IAAIR,aAAatB,iBAAiBS,QAAQ;gBAC7C,MAAMqB,YAAYlC,YAAYa;gBAC9BuB,KAAIC,KAAK,CAACH;YACZ;QACF;IACF;IAEA,IAAIJ,eAAeQ,IAAI,IAAIb,YAAY;QACrC,MAAM,IAAI1B,iBAAiB;eAAI+B;SAAe,CAACS,IAAI,CAAC;IACtD;AACF;AAEA,SAASC,eAAetB,QAAgB;IACtC,OAAOA,SACJuB,OAAO,CAAC,cAAc,MACtBC,UAAU,CAAC,OAAO,KAClBD,OAAO,CAAC,WAAW;AACxB;AAEO,SAASzC,YAAYa,KAAY;IACtC,MAAM,EACJK,QAAQ,EACRJ,KAAK,EACLO,WAAW,EACXsB,MAAM,EACNC,MAAM,EACNC,YAAY,EACZ5B,QAAQ,EACT,GAAGJ;IACJ,IAAI,EAAEiC,iBAAiB,EAAE,GAAGjC;IAC5B,IAAIE,iBAAiBT,8BAA8BQ,OAAO2B,OAAO,CAC/D,OACA;IAGF,IAAIxB,aAAa,SAASA,aAAa,WAAWA,aAAa,SAAS;QACtEF,iBAAiBgC,IAAAA,gBAAI,EAAC,GAAGC,IAAAA,eAAG,EAAC,SAAS,EAAE,EAAEjC,gBAAgB;IAC5D,OAAO,IAAIE,aAAa,WAAW;QACjCF,iBAAiBgC,IAAAA,gBAAI,EAAC,GAAGE,IAAAA,kBAAM,EAAC,WAAW,EAAE,EAAElC,gBAAgB;IACjE,OAAO;QACLA,iBAAiBgC,IAAAA,gBAAI,EAAC,CAAC,MAAM,EAAEhC,gBAAgB;IACjD;IAEA,0CAA0C;IAC1C,+DAA+D;IAC/D,IAAIA,eAAeC,QAAQ,CAAC,qBAAqB;QAC/C,gCAAgC;QAChC,2CAA2C;QAC3C8B,oBAAoB;IACtB;IAEA,MAAMI,oBAAoBV,eAAetB;IAEzC,IAAIiC,UAAU;IAEd,IAAIP,QAAQQ,OAAO;QACjB,MAAM,EAAEC,KAAK,EAAE,GAAGT,OAAOQ,KAAK;QAC9BD,UAAU,GAAGD,kBAAkB,CAAC,EAAEG,MAAMC,IAAI,GAAG,EAAE,CAAC,EAChDD,MAAME,MAAM,GAAG,EAChB,EAAE,EAAExC,gBAAgB;IACvB,OAAO,IAAImC,mBAAmB;QAC5BC,UAAU,GAAGD,kBAAkB,EAAE,EAAEnC,gBAAgB;IACrD,OAAO;QACLoC,UAAUpC;IACZ;IACAoC,WAAW;IAEX,IAAItC,MAAM2C,SAAS,EAAE;QACnBL,WAAWtC,MAAM2C,SAAS,CAACC,OAAO,KAAK;IACzC;IAEA,IAAIpC,aAAa;QACf,IACEA,YAAYqC,IAAI,KAAK,UACrBrC,YAAYsC,KAAK,CAAC3C,QAAQ,CAAC,CAAC,yBAAyB,CAAC,GACtD;YACAmC,WACE;YACFA,WAAW;YACXA,WAAW;QACb,OAAO;YACLA,WAAW7C,8BAA8Be,eAAe;QAC1D;IACF;IAEA,oDAAoD;IACpD,IAAId,kBAAkBoC,QAAQ;QAC5BQ,WAAW7C,8BAA8BqC,UAAU;IACrD;IAEA,iEAAiE;IACjE,KAAK,MAAMiB,cAAc/C,MAAMgD,iBAAiB,IAAI,EAAE,CAAE;QACtD,IAAID,WAAWJ,SAAS,EAAE;YACxB,MAAMM,qBAAqBtB,eACzBoB,WAAWhB,MAAM,CAACA,MAAM,CAAC1B,QAAQ;YAEnC,MAAM6C,MAAMH,WAAWhB,MAAM,CAACQ,KAAK,GAC/B,CAAC,CAAC,EAAEQ,WAAWhB,MAAM,CAACQ,KAAK,CAACC,KAAK,CAACC,IAAI,GAAG,EAAE,CAAC,EAAEM,WAAWhB,MAAM,CAACQ,KAAK,CAACC,KAAK,CAACE,MAAM,GAAG,GAAG,GACxF;YACJJ,WAAW,GAAGS,WAAWvC,WAAW,CAAC,GAAG,EAAEyC,qBAAqBC,IAAI,EAAE,EAAEH,WAAWJ,SAAS,CAACC,OAAO,GAAG,IAAI,CAAC;QAC7G;IACF;IAEA,IAAIZ,cAAcmB,QAAQ;QACxB,iFAAiF;QACjF,yFAAyF;QACzF,4CAA4C;QAC5Cb,WAAW,CAAC,YAAY,EAAEN,aAAamB,MAAM,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;QACjE,MAAMC,kCACJ,IAAIlC,IAAIc,aAAaqB,GAAG,CAACC,eAAeC,MAAM,CAAC,CAACC,IAAMA,KAAK,OAAO/B,IAAI,KACtEO,aAAamB,MAAM;QACrB,IAAK,IAAIM,IAAI,GAAGA,IAAIzB,aAAamB,MAAM,EAAEM,IAAK;YAC5C,MAAMC,QAAQ1B,YAAY,CAACyB,EAAE;YAC7B,MAAME,QAAQL,cAAcI;YAC5B,IAAIE,cAAc;YAClB,yCAAyC;YACzC,IAAIR,iCAAiC;gBACnCd,WAAW,CAAC,EAAE,EAAEqB,MAAM,GAAG,CAAC;YAC5B,OAAO;gBACL,IAAI3B,aAAamB,MAAM,GAAG,GAAG;oBAC3B,uDAAuD;oBACvDb,WAAW,CAAC,GAAG,EAAEmB,IAAI,GAAG;oBACxB,IAAIE,OAAO;wBACTrB,WAAW,CAAC,EAAE,EAAEqB,MAAM,CAAC,CAAC;oBAC1B;oBACArB,WAAW;gBACb,OAAO,IAAIqB,OAAO;oBAChBrB,WAAW,CAAC,EAAE,EAAEqB,MAAM,IAAI,CAAC;gBAC7B,OAAO;oBACL,qEAAqE;oBACrEC,cAAc;gBAChB;YACF;YACAtB,WAAWuB,iBAAiBH,OAAOE,aAAa,CAACE,gBAAgBJ;QACnE;IACF;IACA,IAAIzB,mBAAmB;QACrBK,WAAWL,oBAAoB;IACjC;IACA,OAAOK;AACT;AAEA,sDAAsD,GACtD,SAASgB,cAAcS,KAAuB;IAC5C,KAAK,MAAMC,QAAQD,MAAO;QACxB,MAAMJ,QAAQK,KAAKL,KAAK;QACxB,IAAIA,SAAS,MAAM,OAAOA;IAC5B;IACA,OAAOM;AACT;AAEA;;;CAGC,GACD,SAASH,gBAAgBC,KAAuB;IAC9C,MAAMG,oBAAoBH,MAAMI,SAAS,CAAC,CAACC,IAAMA,EAAET,KAAK,IAAI;IAC5D,IAAIO,sBAAsB,CAAC,GAAG,OAAO,KAAK,wBAAwB;;IAClE,MAAMP,QAAQI,KAAK,CAACG,kBAAkB,CAACP,KAAK;IAC5C,IAAK,IAAIF,IAAIS,oBAAoB,GAAGT,IAAIM,MAAMZ,MAAM,EAAEM,IAAK;QACzD,MAAMY,YAAYN,KAAK,CAACN,EAAE,CAACE,KAAK;QAChC,IAAIU,aAAa,QAAQA,cAAcV,OAAO;YAC5C,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA,SAASE,iBACPE,KAAuB,EACvBO,MAAc,EACdC,WAAoB;IAEpB,OAAO,GAAGR,MACPV,GAAG,CAAC,CAACW;QACJ,IAAIQ,IAAIF;QACR,IAAIN,KAAKS,MAAM,KAAK,WAAW;YAC7BD,KAAK,CAAC,CAAC,EAAER,KAAKS,MAAM,CAAC,EAAE,CAAC;QAC1B,OAAO;YACL,2CAA2C;YAC3CD,KAAK;QACP;QACAA,KAAKR,KAAKU,IAAI;QACd,IAAIH,eAAeP,KAAKL,KAAK,EAAE;YAC7Ba,KAAK,CAAC,EAAE,EAAER,KAAKL,KAAK,CAAC,CAAC,CAAC;QACzB;QACA,OAAOa;IACT,GACC9C,IAAI,CAAC,MAAM,IAAI,CAAC;AACrB;AAEO,SAASpC,kBAAkBU,KAAY;IAC5C,OAAOA,MAAMI,QAAQ,KAAK,aAAa,CAACuE,mBAAmB3E;AAC7D;AAEA,SAAS2E,mBAAmB3E,KAAY;IACtC,IAAIA,MAAMI,QAAQ,KAAK,aAAaJ,MAAM4E,KAAK,KAAK,UAAU;QAC5D,qCAAqC;QACrC,2EAA2E;QAC3E,IACEnF,8BAA8BO,MAAMC,KAAK,EAAEE,QAAQ,CAAC,sBACpD;YACA,OAAO;QACT;IACF;IAEA,OACEH,MAAMI,QAAQ,KAAK,aAClBJ,CAAAA,MAAMK,QAAQ,CAACwE,KAAK,CAAC,8CAA8C,QAClE,0FAA0F;IAC1F,uBAAuB;IACvB,+DAA+D;IAC/D7E,MAAMK,QAAQ,CAACyE,UAAU,CAAC,2BAA0B;AAE1D;AAEO,SAASrF,8BAA8BsF,MAAoB;IAChE,SAASC,mBAAmBC,GAAW;QACrC,yEAAyE;QACzE,MAAMC,eAAeC,IAAAA,gCAAe,EAACF;QACrC,mDAAmD;QACnD,OAAOC,aAAatD,OAAO,CAAC,gBAAgB,CAACiD,QAAUO,IAAAA,mBAAO,EAACP;IACjE;IAEA,OAAQE,OAAOlC,IAAI;QACjB,KAAK;YACH,OAAOmC,mBAAmBD,OAAOjC,KAAK;QACxC,KAAK;YACH,OAAOZ,IAAAA,gBAAI,EAACC,IAAAA,eAAG,EAAC6C,mBAAmBD,OAAOjC,KAAK;QACjD,KAAK;YACH,OAAOuC,IAAAA,iBAAK,EAACL,mBAAmBD,OAAOjC,KAAK;QAC9C,KAAK;YACH,OAAOiC,OAAOjC,KAAK,CAACO,GAAG,CAAC5D,+BAA+BiC,IAAI,CAAC;QAC9D,KAAK;YACH,OAAOqD,OAAOjC,KAAK,CAACO,GAAG,CAAC5D,+BAA+BiC,IAAI,CAAC;QAC9D;YACE,MAAM,IAAI5B,MAAM,6BAA6BiF;IACjD;AACF;AAEO,SAAS1F,+BACdiG,MAA0B;IAE1B,OAAOA,OAAOC,YAAY,EAAEC,kCAAkC;AAChE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.d.ts b/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbac214e63008cc4e00e1b639428641c0f7baabc --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.d.ts @@ -0,0 +1,8 @@ +/** + * Turns optional fields into fields that are required but accept undefined, i.e. + * `NonPartial<{ x?: number }>` is `{ x: number | undefined }`. + * Source: https://github.com/microsoft/TypeScript/issues/31025#issuecomment-870011852 + * */ +export type NonPartial = { + [K in keyof Required]: T[K]; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.js b/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..8d54f7e7deeceb2ac0aeb5bb68f433f1b345227c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.js @@ -0,0 +1,10 @@ +/** + * Turns optional fields into fields that are required but accept undefined, i.e. + * `NonPartial<{ x?: number }>` is `{ x: number | undefined }`. + * Source: https://github.com/microsoft/TypeScript/issues/31025#issuecomment-870011852 + * */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=typescript-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.js.map b/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e54bb89b80b93a2d26c3ecf0e7e0f86c59a8ff74 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/typescript-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/typescript-utils.ts"],"sourcesContent":["/**\n * Turns optional fields into fields that are required but accept undefined, i.e.\n * `NonPartial<{ x?: number }>` is `{ x: number | undefined }`.\n * Source: https://github.com/microsoft/TypeScript/issues/31025#issuecomment-870011852\n * */\nexport type NonPartial = { [K in keyof Required]: T[K] }\n"],"names":[],"mappings":"AAAA;;;;GAIG","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils.d.ts b/e-commerce/node_modules/next/dist/shared/lib/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f54fd3a549614a428309a7e4665937055a948af4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils.d.ts @@ -0,0 +1,286 @@ +import type { HtmlProps } from './html-context.shared-runtime'; +import type { ComponentType, JSX } from 'react'; +import type { DomainLocale } from '../../server/config'; +import type { Env } from '@next/env'; +import type { IncomingMessage, ServerResponse } from 'http'; +import type { NextRouter } from './router/router'; +import type { ParsedUrlQuery } from 'querystring'; +import type { PreviewData } from '../../types'; +import type { COMPILER_NAMES } from './constants'; +import type fs from 'fs'; +export type NextComponentType = ComponentType & { + /** + * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered. + * Make sure to return plain `Object` without using `Date`, `Map`, `Set`. + * @param context Context of `page` + */ + getInitialProps?(context: Context): InitialProps | Promise; +}; +export type DocumentType = NextComponentType; +export type AppType

= NextComponentType>; +export type AppTreeType = ComponentType; +/** + * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team. + * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting + */ +export declare const WEB_VITALS: readonly ["CLS", "FCP", "INP", "LCP", "TTFB"]; +export type NextWebVitalsMetric = { + id: string; + startTime: number; + value: number; + attribution?: { + [key: string]: unknown; + }; +} & ({ + label: 'web-vital'; + name: (typeof WEB_VITALS)[number]; +} | { + label: 'custom'; + name: 'Next.js-hydration' | 'Next.js-route-change-to-render' | 'Next.js-render'; +}); +export type Enhancer = (Component: C) => C; +export type ComponentsEnhancer = { + enhanceApp?: Enhancer; + enhanceComponent?: Enhancer; +} | Enhancer; +export type RenderPageResult = { + html: string; + head?: Array; +}; +export type RenderPage = (options?: ComponentsEnhancer) => DocumentInitialProps | Promise; +export type BaseContext = { + res?: ServerResponse; + [k: string]: any; +}; +export type NEXT_DATA = { + props: Record; + page: string; + query: ParsedUrlQuery; + buildId: string; + assetPrefix?: string; + nextExport?: boolean; + autoExport?: boolean; + isFallback?: boolean; + isExperimentalCompile?: boolean; + dynamicIds?: (string | number)[]; + err?: Error & { + statusCode?: number; + source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer; + }; + gsp?: boolean; + gssp?: boolean; + customServer?: boolean; + gip?: boolean; + appGip?: boolean; + locale?: string; + locales?: readonly string[]; + defaultLocale?: string; + domainLocales?: readonly DomainLocale[]; + scriptLoader?: any[]; + isPreview?: boolean; + notFoundSrcPage?: string; +}; +/** + * `Next` context + */ +export interface NextPageContext { + /** + * Error object if encountered during rendering + */ + err?: (Error & { + statusCode?: number; + }) | null; + /** + * `HTTP` request object. + */ + req?: IncomingMessage; + /** + * `HTTP` response object. + */ + res?: ServerResponse; + /** + * Path section of `URL`. + */ + pathname: string; + /** + * Query string section of `URL` parsed as an object. + */ + query: ParsedUrlQuery; + /** + * `String` of the actual path including query. + */ + asPath?: string; + /** + * The currently active locale + */ + locale?: string; + /** + * All configured locales + */ + locales?: readonly string[]; + /** + * The configured default locale + */ + defaultLocale?: string; + /** + * `Component` the tree of the App to use if needing to render separately + */ + AppTree: AppTreeType; +} +export type AppContextType = { + Component: NextComponentType; + AppTree: AppTreeType; + ctx: NextPageContext; + router: Router; +}; +export type AppInitialProps = { + pageProps: PageProps; +}; +export type AppPropsType = AppInitialProps & { + Component: NextComponentType; + router: Router; + __N_SSG?: boolean; + __N_SSP?: boolean; +}; +export type DocumentContext = NextPageContext & { + renderPage: RenderPage; + defaultGetInitialProps(ctx: DocumentContext, options?: { + nonce?: string; + }): Promise; +}; +export type DocumentInitialProps = RenderPageResult & { + styles?: React.ReactElement[] | Iterable | JSX.Element; +}; +export type DocumentProps = DocumentInitialProps & HtmlProps; +/** + * Next `API` route request + */ +export interface NextApiRequest extends IncomingMessage { + /** + * Object of `query` values from url + */ + query: Partial<{ + [key: string]: string | string[]; + }>; + /** + * Object of `cookies` from header + */ + cookies: Partial<{ + [key: string]: string; + }>; + body: any; + env: Env; + draftMode?: boolean; + preview?: boolean; + /** + * Preview data set on the request, if any + * */ + previewData?: PreviewData; +} +/** + * Send body of response + */ +type Send = (body: T) => void; +/** + * Next `API` route response + */ +export type NextApiResponse = ServerResponse & { + /** + * Send data `any` data in response + */ + send: Send; + /** + * Send data `json` data in response + */ + json: Send; + status: (statusCode: number) => NextApiResponse; + redirect(url: string): NextApiResponse; + redirect(status: number, url: string): NextApiResponse; + /** + * Set draft mode + */ + setDraftMode: (options: { + enable: boolean; + }) => NextApiResponse; + /** + * Set preview data for Next.js' prerender mode + */ + setPreviewData: (data: object | string, options?: { + /** + * Specifies the number (in seconds) for the preview session to last for. + * The given number will be converted to an integer by rounding down. + * By default, no maximum age is set and the preview session finishes + * when the client shuts down (browser is closed). + */ + maxAge?: number; + /** + * Specifies the path for the preview session to work under. By default, + * the path is considered the "default path", i.e., any pages under "/". + */ + path?: string; + }) => NextApiResponse; + /** + * Clear preview data for Next.js' prerender mode + */ + clearPreviewData: (options?: { + path?: string; + }) => NextApiResponse; + /** + * Revalidate a specific page and regenerate it using On-Demand Incremental + * Static Regeneration. + * The path should be an actual path, not a rewritten path. E.g. for + * "/blog/[slug]" this should be "/blog/post-1". + * @link https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation-with-revalidatepath + */ + revalidate: (urlPath: string, opts?: { + unstable_onlyGenerated?: boolean; + }) => Promise; +}; +/** + * Next `API` route handler + */ +export type NextApiHandler = (req: NextApiRequest, res: NextApiResponse) => unknown | Promise; +/** + * Utils + */ +export declare function execOnce ReturnType>(fn: T): T; +export declare const isAbsoluteUrl: (url: string) => boolean; +export declare function getLocationOrigin(): string; +export declare function getURL(): string; +export declare function getDisplayName

(Component: ComponentType

): string; +export declare function isResSent(res: ServerResponse): boolean; +export declare function normalizeRepeatedSlashes(url: string): string; +export declare function loadGetInitialProps(App: NextComponentType, ctx: C): Promise; +export declare const SP: boolean; +export declare const ST: boolean; +export declare class DecodeError extends Error { +} +export declare class NormalizeError extends Error { +} +export declare class PageNotFoundError extends Error { + code: string; + constructor(page: string); +} +export declare class MissingStaticPage extends Error { + constructor(page: string, message: string); +} +export declare class MiddlewareNotFoundError extends Error { + code: string; + constructor(); +} +export interface CacheFs { + existsSync: typeof fs.existsSync; + readFile: typeof fs.promises.readFile; + readFileSync: typeof fs.readFileSync; + writeFile(f: string, d: any): Promise; + /** Publish a complete file without replacing an existing destination. */ + writeFileAtomic?(f: string, d: any): Promise; + mkdir(dir: string): Promise; + stat(f: string): Promise<{ + mtime: Date; + }>; +} +export declare function stringifyError(error: Error): string; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils.js b/e-commerce/node_modules/next/dist/shared/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..8600158ea9096b4890816848bc5c84fb71e870ff --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils.js @@ -0,0 +1,207 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DecodeError: null, + MiddlewareNotFoundError: null, + MissingStaticPage: null, + NormalizeError: null, + PageNotFoundError: null, + SP: null, + ST: null, + WEB_VITALS: null, + execOnce: null, + getDisplayName: null, + getLocationOrigin: null, + getURL: null, + isAbsoluteUrl: null, + isResSent: null, + loadGetInitialProps: null, + normalizeRepeatedSlashes: null, + stringifyError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DecodeError: function() { + return DecodeError; + }, + MiddlewareNotFoundError: function() { + return MiddlewareNotFoundError; + }, + MissingStaticPage: function() { + return MissingStaticPage; + }, + NormalizeError: function() { + return NormalizeError; + }, + PageNotFoundError: function() { + return PageNotFoundError; + }, + SP: function() { + return SP; + }, + ST: function() { + return ST; + }, + WEB_VITALS: function() { + return WEB_VITALS; + }, + execOnce: function() { + return execOnce; + }, + getDisplayName: function() { + return getDisplayName; + }, + getLocationOrigin: function() { + return getLocationOrigin; + }, + getURL: function() { + return getURL; + }, + isAbsoluteUrl: function() { + return isAbsoluteUrl; + }, + isResSent: function() { + return isResSent; + }, + loadGetInitialProps: function() { + return loadGetInitialProps; + }, + normalizeRepeatedSlashes: function() { + return normalizeRepeatedSlashes; + }, + stringifyError: function() { + return stringifyError; + } +}); +const WEB_VITALS = [ + 'CLS', + 'FCP', + 'INP', + 'LCP', + 'TTFB' +]; +function execOnce(fn) { + let used = false; + let result; + return (...args)=>{ + if (!used) { + used = true; + result = fn(...args); + } + return result; + }; +} +// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 +// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 +const ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/; +const isAbsoluteUrl = (url)=>{ + // Fast path: an absolute URL must start with a letter (the scheme). + // Check for a-z and A-Z without the cost of the regex. + const c = url.charCodeAt(0); + const isLetter = c >= 65 /* A */ && c <= 90 || c >= 97 /* a */ && c <= 122; + /* z */ if (!isLetter) { + return false; + } + return ABSOLUTE_URL_REGEX.test(url); +}; +function getLocationOrigin() { + const { protocol, hostname, port } = window.location; + return `${protocol}//${hostname}${port ? ':' + port : ''}`; +} +function getURL() { + const { href } = window.location; + const origin = getLocationOrigin(); + return href.substring(origin.length); +} +function getDisplayName(Component) { + return typeof Component === 'string' ? Component : Component.displayName || Component.name || 'Unknown'; +} +function isResSent(res) { + return res.finished || res.headersSent; +} +function normalizeRepeatedSlashes(url) { + const urlParts = url.split('?'); + const urlNoQuery = urlParts[0]; + return urlNoQuery// first we replace any non-encoded backslashes with forward + // then normalize repeated forward slashes + .replace(/\\/g, '/').replace(/\/\/+/g, '/') + (urlParts[1] ? `?${urlParts.slice(1).join('?')}` : ''); +} +async function loadGetInitialProps(App, ctx) { + if (process.env.NODE_ENV !== 'production') { + if (App.prototype?.getInitialProps) { + const message = `"${getDisplayName(App)}.getInitialProps()" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.`; + throw new Error(message); + } + } + // when called from _app `ctx` is nested in `ctx` + const res = ctx.res || ctx.ctx && ctx.ctx.res; + if (!App.getInitialProps) { + if (ctx.ctx && ctx.Component) { + // @ts-ignore pageProps default + return { + pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx) + }; + } + return {}; + } + const props = await App.getInitialProps(ctx); + if (res && isResSent(res)) { + return props; + } + if (!props) { + const message = `"${getDisplayName(App)}.getInitialProps()" should resolve to an object. But found "${props}" instead.`; + throw new Error(message); + } + if (process.env.NODE_ENV !== 'production') { + if (Object.keys(props).length === 0 && !ctx.ctx) { + console.warn(`${getDisplayName(App)} returned an empty object from \`getInitialProps\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps`); + } + } + return props; +} +const SP = typeof performance !== 'undefined'; +const ST = SP && [ + 'mark', + 'measure', + 'getEntriesByName' +].every((method)=>typeof performance[method] === 'function'); +class DecodeError extends Error { +} +class NormalizeError extends Error { +} +class PageNotFoundError extends Error { + constructor(page){ + super(); + this.code = 'ENOENT'; + this.name = 'PageNotFoundError'; + this.message = `Cannot find module for page: ${page}`; + } +} +class MissingStaticPage extends Error { + constructor(page, message){ + super(); + this.message = `Failed to load static file for page: ${page} ${message}`; + } +} +class MiddlewareNotFoundError extends Error { + constructor(){ + super(); + this.code = 'ENOENT'; + this.message = `Cannot find the middleware module`; + } +} +function stringifyError(error) { + return JSON.stringify({ + message: error.message, + stack: error.stack + }); +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils.js.map b/e-commerce/node_modules/next/dist/shared/lib/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..674aeb7dd94571e92d38521b3eea2b558f95cd51 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/utils.ts"],"sourcesContent":["import type { HtmlProps } from './html-context.shared-runtime'\nimport type { ComponentType, JSX } from 'react'\nimport type { DomainLocale } from '../../server/config'\nimport type { Env } from '@next/env'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextRouter } from './router/router'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { PreviewData } from '../../types'\nimport type { COMPILER_NAMES } from './constants'\nimport type fs from 'fs'\n\nexport type NextComponentType<\n Context extends BaseContext = NextPageContext,\n InitialProps = {},\n Props = {},\n> = ComponentType & {\n /**\n * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.\n * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.\n * @param context Context of `page`\n */\n getInitialProps?(context: Context): InitialProps | Promise\n}\n\nexport type DocumentType = NextComponentType<\n DocumentContext,\n DocumentInitialProps,\n DocumentProps\n>\n\nexport type AppType

= NextComponentType<\n AppContextType,\n P,\n AppPropsType\n>\n\nexport type AppTreeType = ComponentType<\n AppInitialProps & { [name: string]: any }\n>\n\n/**\n * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.\n * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting\n */\nexport const WEB_VITALS = ['CLS', 'FCP', 'INP', 'LCP', 'TTFB'] as const\nexport type NextWebVitalsMetric = {\n id: string\n startTime: number\n value: number\n attribution?: { [key: string]: unknown }\n} & (\n | {\n label: 'web-vital'\n name: (typeof WEB_VITALS)[number]\n }\n | {\n label: 'custom'\n name:\n | 'Next.js-hydration'\n | 'Next.js-route-change-to-render'\n | 'Next.js-render'\n }\n)\n\nexport type Enhancer = (Component: C) => C\n\nexport type ComponentsEnhancer =\n | {\n enhanceApp?: Enhancer\n enhanceComponent?: Enhancer\n }\n | Enhancer\n\nexport type RenderPageResult = {\n html: string\n head?: Array\n}\n\nexport type RenderPage = (\n options?: ComponentsEnhancer\n) => DocumentInitialProps | Promise\n\nexport type BaseContext = {\n res?: ServerResponse\n [k: string]: any\n}\n\nexport type NEXT_DATA = {\n props: Record\n page: string\n query: ParsedUrlQuery\n buildId: string\n assetPrefix?: string\n nextExport?: boolean\n autoExport?: boolean\n isFallback?: boolean\n isExperimentalCompile?: boolean\n dynamicIds?: (string | number)[]\n err?: Error & {\n statusCode?: number\n source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n }\n gsp?: boolean\n gssp?: boolean\n customServer?: boolean\n gip?: boolean\n appGip?: boolean\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n scriptLoader?: any[]\n isPreview?: boolean\n notFoundSrcPage?: string\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n /**\n * Error object if encountered during rendering\n */\n err?: (Error & { statusCode?: number }) | null\n /**\n * `HTTP` request object.\n */\n req?: IncomingMessage\n /**\n * `HTTP` response object.\n */\n res?: ServerResponse\n /**\n * Path section of `URL`.\n */\n pathname: string\n /**\n * Query string section of `URL` parsed as an object.\n */\n query: ParsedUrlQuery\n /**\n * `String` of the actual path including query.\n */\n asPath?: string\n /**\n * The currently active locale\n */\n locale?: string\n /**\n * All configured locales\n */\n locales?: readonly string[]\n /**\n * The configured default locale\n */\n defaultLocale?: string\n /**\n * `Component` the tree of the App to use if needing to render separately\n */\n AppTree: AppTreeType\n}\n\nexport type AppContextType = {\n Component: NextComponentType\n AppTree: AppTreeType\n ctx: NextPageContext\n router: Router\n}\n\nexport type AppInitialProps = {\n pageProps: PageProps\n}\n\nexport type AppPropsType<\n Router extends NextRouter = NextRouter,\n PageProps = {},\n> = AppInitialProps & {\n Component: NextComponentType\n router: Router\n __N_SSG?: boolean\n __N_SSP?: boolean\n}\n\nexport type DocumentContext = NextPageContext & {\n renderPage: RenderPage\n defaultGetInitialProps(\n ctx: DocumentContext,\n options?: { nonce?: string }\n ): Promise\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n styles?: React.ReactElement[] | Iterable | JSX.Element\n}\n\nexport type DocumentProps = DocumentInitialProps & HtmlProps\n\n/**\n * Next `API` route request\n */\nexport interface NextApiRequest extends IncomingMessage {\n /**\n * Object of `query` values from url\n */\n query: Partial<{\n [key: string]: string | string[]\n }>\n /**\n * Object of `cookies` from header\n */\n cookies: Partial<{\n [key: string]: string\n }>\n\n body: any\n\n env: Env\n\n draftMode?: boolean\n\n preview?: boolean\n /**\n * Preview data set on the request, if any\n * */\n previewData?: PreviewData\n}\n\n/**\n * Send body of response\n */\ntype Send = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse = ServerResponse & {\n /**\n * Send data `any` data in response\n */\n send: Send\n /**\n * Send data `json` data in response\n */\n json: Send\n status: (statusCode: number) => NextApiResponse\n redirect(url: string): NextApiResponse\n redirect(status: number, url: string): NextApiResponse\n\n /**\n * Set draft mode\n */\n setDraftMode: (options: { enable: boolean }) => NextApiResponse\n\n /**\n * Set preview data for Next.js' prerender mode\n */\n setPreviewData: (\n data: object | string,\n options?: {\n /**\n * Specifies the number (in seconds) for the preview session to last for.\n * The given number will be converted to an integer by rounding down.\n * By default, no maximum age is set and the preview session finishes\n * when the client shuts down (browser is closed).\n */\n maxAge?: number\n /**\n * Specifies the path for the preview session to work under. By default,\n * the path is considered the \"default path\", i.e., any pages under \"/\".\n */\n path?: string\n }\n ) => NextApiResponse\n\n /**\n * Clear preview data for Next.js' prerender mode\n */\n clearPreviewData: (options?: { path?: string }) => NextApiResponse\n\n /**\n * Revalidate a specific page and regenerate it using On-Demand Incremental\n * Static Regeneration.\n * The path should be an actual path, not a rewritten path. E.g. for\n * \"/blog/[slug]\" this should be \"/blog/post-1\".\n * @link https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation-with-revalidatepath\n */\n revalidate: (\n urlPath: string,\n opts?: {\n unstable_onlyGenerated?: boolean\n }\n ) => Promise\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler = (\n req: NextApiRequest,\n res: NextApiResponse\n) => unknown | Promise\n\n/**\n * Utils\n */\nexport function execOnce ReturnType>(\n fn: T\n): T {\n let used = false\n let result: ReturnType\n\n return ((...args: any[]) => {\n if (!used) {\n used = true\n result = fn(...args)\n }\n return result\n }) as T\n}\n\n// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1\n// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\nconst ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\\d+\\-.]*?:/\nexport const isAbsoluteUrl = (url: string) => {\n // Fast path: an absolute URL must start with a letter (the scheme).\n // Check for a-z and A-Z without the cost of the regex.\n const c = url.charCodeAt(0)\n const isLetter =\n (c >= 65 /* A */ && c <= 90) /* Z */ ||\n (c >= 97 /* a */ && c <= 122) /* z */\n if (!isLetter) {\n return false\n }\n\n return ABSOLUTE_URL_REGEX.test(url)\n}\n\nexport function getLocationOrigin() {\n const { protocol, hostname, port } = window.location\n return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n const { href } = window.location\n const origin = getLocationOrigin()\n return href.substring(origin.length)\n}\n\nexport function getDisplayName

(Component: ComponentType

) {\n return typeof Component === 'string'\n ? Component\n : Component.displayName || Component.name || 'Unknown'\n}\n\nexport function isResSent(res: ServerResponse) {\n return res.finished || res.headersSent\n}\n\nexport function normalizeRepeatedSlashes(url: string) {\n const urlParts = url.split('?')\n const urlNoQuery = urlParts[0]\n\n return (\n urlNoQuery\n // first we replace any non-encoded backslashes with forward\n // then normalize repeated forward slashes\n .replace(/\\\\/g, '/')\n .replace(/\\/\\/+/g, '/') +\n (urlParts[1] ? `?${urlParts.slice(1).join('?')}` : '')\n )\n}\n\nexport async function loadGetInitialProps<\n C extends BaseContext,\n IP = {},\n P = {},\n>(App: NextComponentType, ctx: C): Promise {\n if (process.env.NODE_ENV !== 'production') {\n if (App.prototype?.getInitialProps) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.`\n throw new Error(message)\n }\n }\n // when called from _app `ctx` is nested in `ctx`\n const res = ctx.res || (ctx.ctx && ctx.ctx.res)\n\n if (!App.getInitialProps) {\n if (ctx.ctx && ctx.Component) {\n // @ts-ignore pageProps default\n return {\n pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx),\n }\n }\n return {} as IP\n }\n\n const props = await App.getInitialProps(ctx)\n\n if (res && isResSent(res)) {\n return props\n }\n\n if (!props) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" should resolve to an object. But found \"${props}\" instead.`\n throw new Error(message)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (Object.keys(props).length === 0 && !ctx.ctx) {\n console.warn(\n `${getDisplayName(\n App\n )} returned an empty object from \\`getInitialProps\\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps`\n )\n }\n }\n\n return props\n}\n\nexport const SP = typeof performance !== 'undefined'\nexport const ST =\n SP &&\n (['mark', 'measure', 'getEntriesByName'] as const).every(\n (method) => typeof performance[method] === 'function'\n )\n\nexport class DecodeError extends Error {}\nexport class NormalizeError extends Error {}\nexport class PageNotFoundError extends Error {\n code: string\n\n constructor(page: string) {\n super()\n this.code = 'ENOENT'\n this.name = 'PageNotFoundError'\n this.message = `Cannot find module for page: ${page}`\n }\n}\n\nexport class MissingStaticPage extends Error {\n constructor(page: string, message: string) {\n super()\n this.message = `Failed to load static file for page: ${page} ${message}`\n }\n}\n\nexport class MiddlewareNotFoundError extends Error {\n code: string\n constructor() {\n super()\n this.code = 'ENOENT'\n this.message = `Cannot find the middleware module`\n }\n}\n\nexport interface CacheFs {\n existsSync: typeof fs.existsSync\n readFile: typeof fs.promises.readFile\n readFileSync: typeof fs.readFileSync\n writeFile(f: string, d: any): Promise\n /** Publish a complete file without replacing an existing destination. */\n writeFileAtomic?(f: string, d: any): Promise\n mkdir(dir: string): Promise\n stat(f: string): Promise<{ mtime: Date }>\n}\n\nexport function stringifyError(error: Error) {\n return JSON.stringify({ message: error.message, stack: error.stack })\n}\n"],"names":["DecodeError","MiddlewareNotFoundError","MissingStaticPage","NormalizeError","PageNotFoundError","SP","ST","WEB_VITALS","execOnce","getDisplayName","getLocationOrigin","getURL","isAbsoluteUrl","isResSent","loadGetInitialProps","normalizeRepeatedSlashes","stringifyError","fn","used","result","args","ABSOLUTE_URL_REGEX","url","c","charCodeAt","isLetter","test","protocol","hostname","port","window","location","href","origin","substring","length","Component","displayName","name","res","finished","headersSent","urlParts","split","urlNoQuery","replace","slice","join","App","ctx","process","env","NODE_ENV","prototype","getInitialProps","message","Error","pageProps","props","Object","keys","console","warn","performance","every","method","constructor","page","code","error","JSON","stringify","stack"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+aaA,WAAW;eAAXA;;IAoBAC,uBAAuB;eAAvBA;;IAPAC,iBAAiB;eAAjBA;;IAZAC,cAAc;eAAdA;;IACAC,iBAAiB;eAAjBA;;IATAC,EAAE;eAAFA;;IACAC,EAAE;eAAFA;;IA7XAC,UAAU;eAAVA;;IAqQGC,QAAQ;eAARA;;IA2CAC,cAAc;eAAdA;;IAXAC,iBAAiB;eAAjBA;;IAKAC,MAAM;eAANA;;IAnBHC,aAAa;eAAbA;;IA+BGC,SAAS;eAATA;;IAkBMC,mBAAmB;eAAnBA;;IAdNC,wBAAwB;eAAxBA;;IAiHAC,cAAc;eAAdA;;;AA3aT,MAAMT,aAAa;IAAC;IAAO;IAAO;IAAO;IAAO;CAAO;AAqQvD,SAASC,SACdS,EAAK;IAEL,IAAIC,OAAO;IACX,IAAIC;IAEJ,OAAQ,CAAC,GAAGC;QACV,IAAI,CAACF,MAAM;YACTA,OAAO;YACPC,SAASF,MAAMG;QACjB;QACA,OAAOD;IACT;AACF;AAEA,0DAA0D;AAC1D,gEAAgE;AAChE,MAAME,qBAAqB;AACpB,MAAMT,gBAAgB,CAACU;IAC5B,oEAAoE;IACpE,uDAAuD;IACvD,MAAMC,IAAID,IAAIE,UAAU,CAAC;IACzB,MAAMC,WACJ,AAACF,KAAK,GAAG,KAAK,OAAMA,KAAK,MACxBA,KAAK,GAAG,KAAK,OAAMA,KAAK;IAAK,KAAK,GACrC,IAAI,CAACE,UAAU;QACb,OAAO;IACT;IAEA,OAAOJ,mBAAmBK,IAAI,CAACJ;AACjC;AAEO,SAASZ;IACd,MAAM,EAAEiB,QAAQ,EAAEC,QAAQ,EAAEC,IAAI,EAAE,GAAGC,OAAOC,QAAQ;IACpD,OAAO,GAAGJ,SAAS,EAAE,EAAEC,WAAWC,OAAO,MAAMA,OAAO,IAAI;AAC5D;AAEO,SAASlB;IACd,MAAM,EAAEqB,IAAI,EAAE,GAAGF,OAAOC,QAAQ;IAChC,MAAME,SAASvB;IACf,OAAOsB,KAAKE,SAAS,CAACD,OAAOE,MAAM;AACrC;AAEO,SAAS1B,eAAkB2B,SAA2B;IAC3D,OAAO,OAAOA,cAAc,WACxBA,YACAA,UAAUC,WAAW,IAAID,UAAUE,IAAI,IAAI;AACjD;AAEO,SAASzB,UAAU0B,GAAmB;IAC3C,OAAOA,IAAIC,QAAQ,IAAID,IAAIE,WAAW;AACxC;AAEO,SAAS1B,yBAAyBO,GAAW;IAClD,MAAMoB,WAAWpB,IAAIqB,KAAK,CAAC;IAC3B,MAAMC,aAAaF,QAAQ,CAAC,EAAE;IAE9B,OACEE,UACE,4DAA4D;IAC5D,0CAA0C;KACzCC,OAAO,CAAC,OAAO,KACfA,OAAO,CAAC,UAAU,OACpBH,CAAAA,QAAQ,CAAC,EAAE,GAAG,CAAC,CAAC,EAAEA,SAASI,KAAK,CAAC,GAAGC,IAAI,CAAC,MAAM,GAAG,EAAC;AAExD;AAEO,eAAejC,oBAIpBkC,GAAgC,EAAEC,GAAM;IACxC,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;QACzC,IAAIJ,IAAIK,SAAS,EAAEC,iBAAiB;YAClC,MAAMC,UAAU,CAAC,CAAC,EAAE9C,eAClBuC,KACA,2JAA2J,CAAC;YAC9J,MAAM,IAAIQ,MAAMD;QAClB;IACF;IACA,iDAAiD;IACjD,MAAMhB,MAAMU,IAAIV,GAAG,IAAKU,IAAIA,GAAG,IAAIA,IAAIA,GAAG,CAACV,GAAG;IAE9C,IAAI,CAACS,IAAIM,eAAe,EAAE;QACxB,IAAIL,IAAIA,GAAG,IAAIA,IAAIb,SAAS,EAAE;YAC5B,+BAA+B;YAC/B,OAAO;gBACLqB,WAAW,MAAM3C,oBAAoBmC,IAAIb,SAAS,EAAEa,IAAIA,GAAG;YAC7D;QACF;QACA,OAAO,CAAC;IACV;IAEA,MAAMS,QAAQ,MAAMV,IAAIM,eAAe,CAACL;IAExC,IAAIV,OAAO1B,UAAU0B,MAAM;QACzB,OAAOmB;IACT;IAEA,IAAI,CAACA,OAAO;QACV,MAAMH,UAAU,CAAC,CAAC,EAAE9C,eAClBuC,KACA,4DAA4D,EAAEU,MAAM,UAAU,CAAC;QACjF,MAAM,IAAIF,MAAMD;IAClB;IAEA,IAAIL,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;QACzC,IAAIO,OAAOC,IAAI,CAACF,OAAOvB,MAAM,KAAK,KAAK,CAACc,IAAIA,GAAG,EAAE;YAC/CY,QAAQC,IAAI,CACV,GAAGrD,eACDuC,KACA,+KAA+K,CAAC;QAEtL;IACF;IAEA,OAAOU;AACT;AAEO,MAAMrD,KAAK,OAAO0D,gBAAgB;AAClC,MAAMzD,KACXD,MACA,AAAC;IAAC;IAAQ;IAAW;CAAmB,CAAW2D,KAAK,CACtD,CAACC,SAAW,OAAOF,WAAW,CAACE,OAAO,KAAK;AAGxC,MAAMjE,oBAAoBwD;AAAO;AACjC,MAAMrD,uBAAuBqD;AAAO;AACpC,MAAMpD,0BAA0BoD;IAGrCU,YAAYC,IAAY,CAAE;QACxB,KAAK;QACL,IAAI,CAACC,IAAI,GAAG;QACZ,IAAI,CAAC9B,IAAI,GAAG;QACZ,IAAI,CAACiB,OAAO,GAAG,CAAC,6BAA6B,EAAEY,MAAM;IACvD;AACF;AAEO,MAAMjE,0BAA0BsD;IACrCU,YAAYC,IAAY,EAAEZ,OAAe,CAAE;QACzC,KAAK;QACL,IAAI,CAACA,OAAO,GAAG,CAAC,qCAAqC,EAAEY,KAAK,CAAC,EAAEZ,SAAS;IAC1E;AACF;AAEO,MAAMtD,gCAAgCuD;IAE3CU,aAAc;QACZ,KAAK;QACL,IAAI,CAACE,IAAI,GAAG;QACZ,IAAI,CAACb,OAAO,GAAG,CAAC,iCAAiC,CAAC;IACpD;AACF;AAaO,SAASvC,eAAeqD,KAAY;IACzC,OAAOC,KAAKC,SAAS,CAAC;QAAEhB,SAASc,MAAMd,OAAO;QAAEiB,OAAOH,MAAMG,KAAK;IAAC;AACrE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.d.ts b/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97f904a1a63faa44b4c8b59b7e8fbbbec270284e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.d.ts @@ -0,0 +1,2 @@ +declare let errorOnce: (_: string) => void; +export { errorOnce }; diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.js b/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.js new file mode 100644 index 0000000000000000000000000000000000000000..b980285114f58af67545e6a79bbdf421225c3247 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "errorOnce", { + enumerable: true, + get: function() { + return errorOnce; + } +}); +let errorOnce = (_)=>{}; +if (process.env.NODE_ENV !== 'production') { + const errors = new Set(); + errorOnce = (msg)=>{ + if (!errors.has(msg)) { + console.error(msg); + } + errors.add(msg); + }; +} + +//# sourceMappingURL=error-once.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.js.map b/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ede922ef750d114b65b5f8e2d01c6586767d8972 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/error-once.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/utils/error-once.ts"],"sourcesContent":["let errorOnce = (_: string) => {}\nif (process.env.NODE_ENV !== 'production') {\n const errors = new Set()\n errorOnce = (msg: string) => {\n if (!errors.has(msg)) {\n console.error(msg)\n }\n errors.add(msg)\n }\n}\n\nexport { errorOnce }\n"],"names":["errorOnce","_","process","env","NODE_ENV","errors","Set","msg","has","console","error","add"],"mappings":";;;;+BAWSA;;;eAAAA;;;AAXT,IAAIA,YAAY,CAACC,KAAe;AAChC,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzC,MAAMC,SAAS,IAAIC;IACnBN,YAAY,CAACO;QACX,IAAI,CAACF,OAAOG,GAAG,CAACD,MAAM;YACpBE,QAAQC,KAAK,CAACH;QAChB;QACAF,OAAOM,GAAG,CAACJ;IACb;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.d.ts b/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f20258b0e98356ea26628dbb8bdc20353221ad1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.d.ts @@ -0,0 +1,3 @@ +export declare function describeStringPropertyAccess(target: string, prop: string): string; +export declare function describeHasCheckingStringProperty(target: string, prop: string): string; +export declare const wellKnownProperties: Set; diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.js b/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..375c4c7b90953a9a10820d0b92848c0e8d276c13 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.js @@ -0,0 +1,69 @@ +// This regex will have fast negatives meaning valid identifiers may not pass +// this test. However this is only used during static generation to provide hints +// about why a page bailed out of some or all prerendering and we can use bracket notation +// for example while `ಠ_ಠ` is a valid identifier it's ok to print `searchParams['ಠ_ಠ']` +// even if this would have been fine too `searchParams.ಠ_ಠ` +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + describeHasCheckingStringProperty: null, + describeStringPropertyAccess: null, + wellKnownProperties: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + describeHasCheckingStringProperty: function() { + return describeHasCheckingStringProperty; + }, + describeStringPropertyAccess: function() { + return describeStringPropertyAccess; + }, + wellKnownProperties: function() { + return wellKnownProperties; + } +}); +const isDefinitelyAValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/; +function describeStringPropertyAccess(target, prop) { + if (isDefinitelyAValidIdentifier.test(prop)) { + return `\`${target}.${prop}\``; + } + return `\`${target}[${JSON.stringify(prop)}]\``; +} +function describeHasCheckingStringProperty(target, prop) { + const stringifiedProp = JSON.stringify(prop); + return `\`Reflect.has(${target}, ${stringifiedProp})\`, \`${stringifiedProp} in ${target}\`, or similar`; +} +const wellKnownProperties = new Set([ + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'toString', + 'valueOf', + 'toLocaleString', + // Promise prototype + 'then', + 'catch', + 'finally', + // React Promise extension + 'status', + // 'value', + // 'error', + // React introspection + 'displayName', + '_debugInfo', + // Common tested properties + 'toJSON', + '$$typeof', + '__esModule', + // Tested by flight when checking for iterables + '@@iterator' +]); + +//# sourceMappingURL=reflect-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.js.map b/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5ed26d221a6dc9a140f58c328daa9fd2d3db2795 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/reflect-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/utils/reflect-utils.ts"],"sourcesContent":["// This regex will have fast negatives meaning valid identifiers may not pass\n// this test. However this is only used during static generation to provide hints\n// about why a page bailed out of some or all prerendering and we can use bracket notation\n// for example while `ಠ_ಠ` is a valid identifier it's ok to print `searchParams['ಠ_ಠ']`\n// even if this would have been fine too `searchParams.ಠ_ಠ`\nconst isDefinitelyAValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/\n\nexport function describeStringPropertyAccess(target: string, prop: string) {\n if (isDefinitelyAValidIdentifier.test(prop)) {\n return `\\`${target}.${prop}\\``\n }\n return `\\`${target}[${JSON.stringify(prop)}]\\``\n}\n\nexport function describeHasCheckingStringProperty(\n target: string,\n prop: string\n) {\n const stringifiedProp = JSON.stringify(prop)\n return `\\`Reflect.has(${target}, ${stringifiedProp})\\`, \\`${stringifiedProp} in ${target}\\`, or similar`\n}\n\nexport const wellKnownProperties = new Set([\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toString',\n 'valueOf',\n 'toLocaleString',\n\n // Promise prototype\n 'then',\n 'catch',\n 'finally',\n\n // React Promise extension\n 'status',\n // 'value',\n // 'error',\n\n // React introspection\n 'displayName',\n '_debugInfo',\n\n // Common tested properties\n 'toJSON',\n '$$typeof',\n '__esModule',\n\n // Tested by flight when checking for iterables\n '@@iterator',\n])\n"],"names":["describeHasCheckingStringProperty","describeStringPropertyAccess","wellKnownProperties","isDefinitelyAValidIdentifier","target","prop","test","JSON","stringify","stringifiedProp","Set"],"mappings":"AAAA,6EAA6E;AAC7E,iFAAiF;AACjF,0FAA0F;AAC1F,uFAAuF;AACvF,2DAA2D;;;;;;;;;;;;;;;;;IAU3CA,iCAAiC;eAAjCA;;IAPAC,4BAA4B;eAA5BA;;IAeHC,mBAAmB;eAAnBA;;;AAjBb,MAAMC,+BAA+B;AAE9B,SAASF,6BAA6BG,MAAc,EAAEC,IAAY;IACvE,IAAIF,6BAA6BG,IAAI,CAACD,OAAO;QAC3C,OAAO,CAAC,EAAE,EAAED,OAAO,CAAC,EAAEC,KAAK,EAAE,CAAC;IAChC;IACA,OAAO,CAAC,EAAE,EAAED,OAAO,CAAC,EAAEG,KAAKC,SAAS,CAACH,MAAM,GAAG,CAAC;AACjD;AAEO,SAASL,kCACdI,MAAc,EACdC,IAAY;IAEZ,MAAMI,kBAAkBF,KAAKC,SAAS,CAACH;IACvC,OAAO,CAAC,cAAc,EAAED,OAAO,EAAE,EAAEK,gBAAgB,OAAO,EAAEA,gBAAgB,IAAI,EAAEL,OAAO,cAAc,CAAC;AAC1G;AAEO,MAAMF,sBAAsB,IAAIQ,IAAI;IACzC;IACA;IACA;IACA;IACA;IACA;IAEA,oBAAoB;IACpB;IACA;IACA;IAEA,0BAA0B;IAC1B;IACA,WAAW;IACX,WAAW;IAEX,sBAAsB;IACtB;IACA;IAEA,2BAA2B;IAC3B;IACA;IACA;IAEA,+CAA+C;IAC/C;CACD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.d.ts b/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c81b0cff9911873f63e7cc837a8b17255da9329 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.d.ts @@ -0,0 +1,2 @@ +declare let warnOnce: (_: string) => void; +export { warnOnce }; diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.js b/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.js new file mode 100644 index 0000000000000000000000000000000000000000..88ee101fe991581caa5d6a251bf64b911888ad69 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "warnOnce", { + enumerable: true, + get: function() { + return warnOnce; + } +}); +let warnOnce = (_)=>{}; +if (process.env.NODE_ENV !== 'production') { + const warnings = new Set(); + warnOnce = (msg)=>{ + if (!warnings.has(msg)) { + console.warn(msg); + } + warnings.add(msg); + }; +} + +//# sourceMappingURL=warn-once.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.js.map b/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7cea63147cc9609d93e5220cb1165d6864470e9f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/utils/warn-once.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/utils/warn-once.ts"],"sourcesContent":["let warnOnce = (_: string) => {}\nif (process.env.NODE_ENV !== 'production') {\n const warnings = new Set()\n warnOnce = (msg: string) => {\n if (!warnings.has(msg)) {\n console.warn(msg)\n }\n warnings.add(msg)\n }\n}\n\nexport { warnOnce }\n"],"names":["warnOnce","_","process","env","NODE_ENV","warnings","Set","msg","has","console","warn","add"],"mappings":";;;;+BAWSA;;;eAAAA;;;AAXT,IAAIA,WAAW,CAACC,KAAe;AAC/B,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzC,MAAMC,WAAW,IAAIC;IACrBN,WAAW,CAACO;QACV,IAAI,CAACF,SAASG,GAAG,CAACD,MAAM;YACtBE,QAAQC,IAAI,CAACH;QACf;QACAF,SAASM,GAAG,CAACJ;IACf;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/zod.d.ts b/e-commerce/node_modules/next/dist/shared/lib/zod.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4626fd81a2604e88c6a6fd7f6f6f5d733bf01a59 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/zod.d.ts @@ -0,0 +1,8 @@ +import type { ZodError } from 'next/dist/compiled/zod'; +import { type ZodIssue } from 'next/dist/compiled/zod'; +export declare function normalizeZodErrors(error: ZodError): { + issue: ZodIssue; + message: string; +}[]; +export declare function formatZodError(prefix: string, error: ZodError): Error; +export declare function reportZodError(prefix: string, error: ZodError): void; diff --git a/e-commerce/node_modules/next/dist/shared/lib/zod.js b/e-commerce/node_modules/next/dist/shared/lib/zod.js new file mode 100644 index 0000000000000000000000000000000000000000..907f1811121bb010f45329fd425011b5916f0e49 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/zod.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + formatZodError: null, + normalizeZodErrors: null, + reportZodError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + formatZodError: function() { + return formatZodError; + }, + normalizeZodErrors: function() { + return normalizeZodErrors; + }, + reportZodError: function() { + return reportZodError; + } +}); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _zod = require("next/dist/compiled/zod"); +const _zodvalidationerror = require("next/dist/compiled/zod-validation-error"); +const _log = /*#__PURE__*/ _interop_require_wildcard._(require("../../build/output/log")); +function processZodErrorMessage(issue) { + let message = issue.message; + let path; + if (issue.path.length > 0) { + if (issue.path.length === 1) { + const identifier = issue.path[0]; + if (typeof identifier === 'number') { + // The first identifier inside path is a number + path = `index ${identifier}`; + } else { + path = `"${identifier}"`; + } + } else { + // joined path to be shown in the error message + path = `"${issue.path.reduce((acc, cur)=>{ + if (typeof cur === 'number') { + // array index + return `${acc}[${cur}]`; + } + if (cur.includes('"')) { + // escape quotes + return `${acc}["${cur.replaceAll('"', '\\"')}"]`; + } + // dot notation + const separator = acc.length === 0 ? '' : '.'; + return acc + separator + cur; + }, '')}"`; + } + } else { + path = ''; + } + if (issue.code === 'invalid_type' && issue.received === _zod.ZodParsedType.undefined) { + // Missing key in object. + return `${path} is missing, expected ${issue.expected}`; + } + if (issue.code === 'invalid_enum_value') { + // Remove "Invalid enum value" prefix from zod default error message + return `Expected ${_zod.util.joinValues(issue.options)}, received '${issue.received}' at ${path}`; + } + return message + (path ? ` at ${path}` : ''); +} +function normalizeZodErrors(error) { + return error.issues.flatMap((issue)=>{ + const issues = [ + { + issue, + message: processZodErrorMessage(issue) + } + ]; + if ('unionErrors' in issue) { + for (const unionError of issue.unionErrors){ + issues.push(...normalizeZodErrors(unionError)); + } + } + return issues; + }); +} +function formatZodError(prefix, error) { + return new Error((0, _zodvalidationerror.fromZodError)(error, { + prefix: prefix + }).toString()); +} +function reportZodError(prefix, error) { + _log.error(formatZodError(prefix, error).message); +} + +//# sourceMappingURL=zod.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/zod.js.map b/e-commerce/node_modules/next/dist/shared/lib/zod.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2ace03073adec81347289cfb0d532bb6cbd4614f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/zod.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/zod.ts"],"sourcesContent":["import type { ZodError } from 'next/dist/compiled/zod'\nimport { ZodParsedType, util, type ZodIssue } from 'next/dist/compiled/zod'\nimport { fromZodError } from 'next/dist/compiled/zod-validation-error'\nimport * as Log from '../../build/output/log'\n\nfunction processZodErrorMessage(issue: ZodIssue) {\n let message = issue.message\n\n let path: string\n\n if (issue.path.length > 0) {\n if (issue.path.length === 1) {\n const identifier = issue.path[0]\n if (typeof identifier === 'number') {\n // The first identifier inside path is a number\n path = `index ${identifier}`\n } else {\n path = `\"${identifier}\"`\n }\n } else {\n // joined path to be shown in the error message\n path = `\"${issue.path.reduce((acc, cur) => {\n if (typeof cur === 'number') {\n // array index\n return `${acc}[${cur}]`\n }\n if (cur.includes('\"')) {\n // escape quotes\n return `${acc}[\"${cur.replaceAll('\"', '\\\\\"')}\"]`\n }\n // dot notation\n const separator = acc.length === 0 ? '' : '.'\n return acc + separator + cur\n }, '')}\"`\n }\n } else {\n path = ''\n }\n\n if (\n issue.code === 'invalid_type' &&\n issue.received === ZodParsedType.undefined\n ) {\n // Missing key in object.\n return `${path} is missing, expected ${issue.expected}`\n }\n\n if (issue.code === 'invalid_enum_value') {\n // Remove \"Invalid enum value\" prefix from zod default error message\n return `Expected ${util.joinValues(issue.options)}, received '${\n issue.received\n }' at ${path}`\n }\n\n return message + (path ? ` at ${path}` : '')\n}\n\nexport function normalizeZodErrors(error: ZodError) {\n return error.issues.flatMap((issue) => {\n const issues = [{ issue, message: processZodErrorMessage(issue) }]\n if ('unionErrors' in issue) {\n for (const unionError of issue.unionErrors) {\n issues.push(...normalizeZodErrors(unionError))\n }\n }\n\n return issues\n })\n}\n\nexport function formatZodError(prefix: string, error: ZodError) {\n return new Error(fromZodError(error, { prefix: prefix }).toString())\n}\n\nexport function reportZodError(prefix: string, error: ZodError) {\n Log.error(formatZodError(prefix, error).message)\n}\n"],"names":["formatZodError","normalizeZodErrors","reportZodError","processZodErrorMessage","issue","message","path","length","identifier","reduce","acc","cur","includes","replaceAll","separator","code","received","ZodParsedType","undefined","expected","util","joinValues","options","error","issues","flatMap","unionError","unionErrors","push","prefix","Error","fromZodError","toString","Log"],"mappings":";;;;;;;;;;;;;;;;IAsEgBA,cAAc;eAAdA;;IAbAC,kBAAkB;eAAlBA;;IAiBAC,cAAc;eAAdA;;;;qBAzEmC;oCACtB;+DACR;AAErB,SAASC,uBAAuBC,KAAe;IAC7C,IAAIC,UAAUD,MAAMC,OAAO;IAE3B,IAAIC;IAEJ,IAAIF,MAAME,IAAI,CAACC,MAAM,GAAG,GAAG;QACzB,IAAIH,MAAME,IAAI,CAACC,MAAM,KAAK,GAAG;YAC3B,MAAMC,aAAaJ,MAAME,IAAI,CAAC,EAAE;YAChC,IAAI,OAAOE,eAAe,UAAU;gBAClC,+CAA+C;gBAC/CF,OAAO,CAAC,MAAM,EAAEE,YAAY;YAC9B,OAAO;gBACLF,OAAO,CAAC,CAAC,EAAEE,WAAW,CAAC,CAAC;YAC1B;QACF,OAAO;YACL,+CAA+C;YAC/CF,OAAO,CAAC,CAAC,EAAEF,MAAME,IAAI,CAACG,MAAM,CAAS,CAACC,KAAKC;gBACzC,IAAI,OAAOA,QAAQ,UAAU;oBAC3B,cAAc;oBACd,OAAO,GAAGD,IAAI,CAAC,EAAEC,IAAI,CAAC,CAAC;gBACzB;gBACA,IAAIA,IAAIC,QAAQ,CAAC,MAAM;oBACrB,gBAAgB;oBAChB,OAAO,GAAGF,IAAI,EAAE,EAAEC,IAAIE,UAAU,CAAC,KAAK,OAAO,EAAE,CAAC;gBAClD;gBACA,eAAe;gBACf,MAAMC,YAAYJ,IAAIH,MAAM,KAAK,IAAI,KAAK;gBAC1C,OAAOG,MAAMI,YAAYH;YAC3B,GAAG,IAAI,CAAC,CAAC;QACX;IACF,OAAO;QACLL,OAAO;IACT;IAEA,IACEF,MAAMW,IAAI,KAAK,kBACfX,MAAMY,QAAQ,KAAKC,kBAAa,CAACC,SAAS,EAC1C;QACA,yBAAyB;QACzB,OAAO,GAAGZ,KAAK,sBAAsB,EAAEF,MAAMe,QAAQ,EAAE;IACzD;IAEA,IAAIf,MAAMW,IAAI,KAAK,sBAAsB;QACvC,oEAAoE;QACpE,OAAO,CAAC,SAAS,EAAEK,SAAI,CAACC,UAAU,CAACjB,MAAMkB,OAAO,EAAE,YAAY,EAC5DlB,MAAMY,QAAQ,CACf,KAAK,EAAEV,MAAM;IAChB;IAEA,OAAOD,UAAWC,CAAAA,OAAO,CAAC,IAAI,EAAEA,MAAM,GAAG,EAAC;AAC5C;AAEO,SAASL,mBAAmBsB,KAAe;IAChD,OAAOA,MAAMC,MAAM,CAACC,OAAO,CAAC,CAACrB;QAC3B,MAAMoB,SAAS;YAAC;gBAAEpB;gBAAOC,SAASF,uBAAuBC;YAAO;SAAE;QAClE,IAAI,iBAAiBA,OAAO;YAC1B,KAAK,MAAMsB,cAActB,MAAMuB,WAAW,CAAE;gBAC1CH,OAAOI,IAAI,IAAI3B,mBAAmByB;YACpC;QACF;QAEA,OAAOF;IACT;AACF;AAEO,SAASxB,eAAe6B,MAAc,EAAEN,KAAe;IAC5D,OAAO,IAAIO,MAAMC,IAAAA,gCAAY,EAACR,OAAO;QAAEM,QAAQA;IAAO,GAAGG,QAAQ;AACnE;AAEO,SAAS9B,eAAe2B,MAAc,EAAEN,KAAe;IAC5DU,KAAIV,KAAK,CAACvB,eAAe6B,QAAQN,OAAOlB,OAAO;AACjD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/styled-jsx/types/css.d.ts b/e-commerce/node_modules/next/dist/styled-jsx/types/css.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9603111b8f50c59e4a38c98a278d85ebdc7892f0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/styled-jsx/types/css.d.ts @@ -0,0 +1,18 @@ +// Definitions by: @types/styled-jsx + +declare module 'styled-jsx/css' { + import type { JSX } from "react"; + + function css(chunks: TemplateStringsArray, ...args: any[]): JSX.Element + namespace css { + export function global( + chunks: TemplateStringsArray, + ...args: any[] + ): JSX.Element + export function resolve( + chunks: TemplateStringsArray, + ...args: any[] + ): { className: string; styles: JSX.Element } + } + export = css +} diff --git a/e-commerce/node_modules/next/dist/styled-jsx/types/global.d.ts b/e-commerce/node_modules/next/dist/styled-jsx/types/global.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af103a71f4a6e49023c5d69522ba10af8533e111 --- /dev/null +++ b/e-commerce/node_modules/next/dist/styled-jsx/types/global.d.ts @@ -0,0 +1,8 @@ +import React from 'react' + +declare module 'react' { + interface StyleHTMLAttributes extends HTMLAttributes { + jsx?: boolean + global?: boolean + } +} diff --git a/e-commerce/node_modules/next/dist/styled-jsx/types/index.d.ts b/e-commerce/node_modules/next/dist/styled-jsx/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bc51ef9f04110c09de80d694d4c96f6a7ff7852 --- /dev/null +++ b/e-commerce/node_modules/next/dist/styled-jsx/types/index.d.ts @@ -0,0 +1,24 @@ +/// +/// +/// +/// + +declare module 'styled-jsx' { + import type { JSX } from "react"; + + export type StyledJsxStyleRegistry = { + styles(options?: { nonce?: string }): JSX.Element[] + flush(): void + add(props: any): void + remove(props: any): void + } + export function useStyleRegistry(): StyledJsxStyleRegistry + export function StyleRegistry({ + children, + registry + }: { + children: JSX.Element | import('react').ReactNode + registry?: StyledJsxStyleRegistry + }): JSX.Element + export function createStyleRegistry(): StyledJsxStyleRegistry +} diff --git a/e-commerce/node_modules/next/dist/styled-jsx/types/macro.d.ts b/e-commerce/node_modules/next/dist/styled-jsx/types/macro.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3efb9264ec8e4c1a3b4049ce6de50fddedf7bc98 --- /dev/null +++ b/e-commerce/node_modules/next/dist/styled-jsx/types/macro.d.ts @@ -0,0 +1,15 @@ +declare module 'styled-jsx/macro' { + import type { JSX } from "react"; + + namespace macro { + function resolve( + chunks: TemplateStringsArray, + ...args: any[] + ): { + className: string + styles: JSX.Element + } + } + + export = macro +} diff --git a/e-commerce/node_modules/next/dist/styled-jsx/types/style.d.ts b/e-commerce/node_modules/next/dist/styled-jsx/types/style.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b58bcf33789f72d4bb91182512028422db78f8a --- /dev/null +++ b/e-commerce/node_modules/next/dist/styled-jsx/types/style.d.ts @@ -0,0 +1,3 @@ +declare module 'styled-jsx/style' { + export default function JSXStyle(props: any): null +} diff --git a/e-commerce/node_modules/next/dist/telemetry/agent-name.d.ts b/e-commerce/node_modules/next/dist/telemetry/agent-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c7b7edf55327bff799e62bd8cbc8ae079a04faa --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/agent-name.d.ts @@ -0,0 +1,13 @@ +/** + * Detects the AI coding agent (if any) driving the current process and resolves + * to its name, or `null` when no agent is detected. + * + * Detection is delegated to `@vercel/detect-agent`, which performs an async + * filesystem probe (e.g. for Devin) in addition to environment-variable checks, + * so it can be relatively expensive. The detected agent cannot change over the + * lifetime of the process, so we memoize the promise: the first call runs + * detection once, and every subsequent call resolves against the already + * settled promise. Any detection failure is treated as "no agent" so telemetry + * never throws on this path. + */ +export declare function getAgentName(): Promise; diff --git a/e-commerce/node_modules/next/dist/telemetry/agent-name.js b/e-commerce/node_modules/next/dist/telemetry/agent-name.js new file mode 100644 index 0000000000000000000000000000000000000000..ddd65f489af764424ddce97800d458b5a63fdce7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/agent-name.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getAgentName", { + enumerable: true, + get: function() { + return getAgentName; + } +}); +const _detectagent = require("next/dist/compiled/@vercel/detect-agent"); +let agentNamePromise; +function getAgentName() { + if (!agentNamePromise) { + agentNamePromise = (0, _detectagent.determineAgent)().then((result)=>result.isAgent ? result.agent.name : null).catch(()=>null); + } + return agentNamePromise; +} + +//# sourceMappingURL=agent-name.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/agent-name.js.map b/e-commerce/node_modules/next/dist/telemetry/agent-name.js.map new file mode 100644 index 0000000000000000000000000000000000000000..52ccb4d1a1c4d9a9cd0d3893f0e62bf49b221e05 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/agent-name.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/agent-name.ts"],"sourcesContent":["import { determineAgent } from 'next/dist/compiled/@vercel/detect-agent'\n\nlet agentNamePromise: Promise | undefined\n\n/**\n * Detects the AI coding agent (if any) driving the current process and resolves\n * to its name, or `null` when no agent is detected.\n *\n * Detection is delegated to `@vercel/detect-agent`, which performs an async\n * filesystem probe (e.g. for Devin) in addition to environment-variable checks,\n * so it can be relatively expensive. The detected agent cannot change over the\n * lifetime of the process, so we memoize the promise: the first call runs\n * detection once, and every subsequent call resolves against the already\n * settled promise. Any detection failure is treated as \"no agent\" so telemetry\n * never throws on this path.\n */\nexport function getAgentName(): Promise {\n if (!agentNamePromise) {\n agentNamePromise = determineAgent()\n .then((result) => (result.isAgent ? result.agent.name : null))\n .catch(() => null)\n }\n\n return agentNamePromise\n}\n"],"names":["getAgentName","agentNamePromise","determineAgent","then","result","isAgent","agent","name","catch"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;6BAhBe;AAE/B,IAAIC;AAcG,SAASD;IACd,IAAI,CAACC,kBAAkB;QACrBA,mBAAmBC,IAAAA,2BAAc,IAC9BC,IAAI,CAAC,CAACC,SAAYA,OAAOC,OAAO,GAAGD,OAAOE,KAAK,CAACC,IAAI,GAAG,MACvDC,KAAK,CAAC,IAAM;IACjB;IAEA,OAAOP;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.d.ts b/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..02dc60f984fe899fcf75aa98137f98aaa6fffc33 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.d.ts @@ -0,0 +1,18 @@ +type AnonymousMeta = { + systemPlatform: NodeJS.Platform; + systemRelease: string; + systemArchitecture: string; + cpuCount: number; + cpuModel: string | null; + cpuSpeed: number | null; + memoryInMb: number; + isDocker: boolean; + isNowDev: boolean; + isWsl: boolean; + isCI: boolean; + ciName: string | null; + nextVersion: string; + agentName: string | null; +}; +export declare function getAnonymousMeta(): Promise; +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.js b/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.js new file mode 100644 index 0000000000000000000000000000000000000000..285bcae6e33f3750200af1b98722e1b7052fa1eb --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getAnonymousMeta", { + enumerable: true, + get: function() { + return getAnonymousMeta; + } +}); +const _isdocker = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/is-docker")); +const _iswsl = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/is-wsl")); +const _os = /*#__PURE__*/ _interop_require_default(require("os")); +const _ciinfo = /*#__PURE__*/ _interop_require_wildcard(require("../server/ci-info")); +const _agentname = require("./agent-name"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +let traits; +async function getAnonymousMeta() { + if (traits) { + return traits; + } + const cpus = _os.default.cpus() || []; + const { NOW_REGION } = process.env; + traits = { + // Software information + systemPlatform: _os.default.platform(), + systemRelease: _os.default.release(), + systemArchitecture: _os.default.arch(), + // Machine information + cpuCount: cpus.length, + cpuModel: cpus.length ? cpus[0].model : null, + cpuSpeed: cpus.length ? cpus[0].speed : null, + memoryInMb: Math.trunc(_os.default.totalmem() / Math.pow(1024, 2)), + // Environment information + isDocker: (0, _isdocker.default)(), + isNowDev: NOW_REGION === 'dev1', + isWsl: _iswsl.default, + isCI: _ciinfo.isCI, + ciName: _ciinfo.isCI && _ciinfo.name || null, + nextVersion: "16.4.0", + agentName: await (0, _agentname.getAgentName)() + }; + return traits; +} + +//# sourceMappingURL=anonymous-meta.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.js.map b/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.js.map new file mode 100644 index 0000000000000000000000000000000000000000..633d3bafcedcb9365a47ff1f9ad415a6198e4747 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/anonymous-meta.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/anonymous-meta.ts"],"sourcesContent":["import isDockerFunction from 'next/dist/compiled/is-docker'\nimport isWslBoolean from 'next/dist/compiled/is-wsl'\nimport os from 'os'\n\nimport * as ciEnvironment from '../server/ci-info'\nimport { getAgentName } from './agent-name'\n\ntype AnonymousMeta = {\n systemPlatform: NodeJS.Platform\n systemRelease: string\n systemArchitecture: string\n cpuCount: number\n cpuModel: string | null\n cpuSpeed: number | null\n memoryInMb: number\n isDocker: boolean\n isNowDev: boolean\n isWsl: boolean\n isCI: boolean\n ciName: string | null\n nextVersion: string\n agentName: string | null\n}\n\nlet traits: AnonymousMeta | undefined\n\nexport async function getAnonymousMeta(): Promise {\n if (traits) {\n return traits\n }\n\n const cpus = os.cpus() || []\n const { NOW_REGION } = process.env\n traits = {\n // Software information\n systemPlatform: os.platform(),\n systemRelease: os.release(),\n systemArchitecture: os.arch(),\n // Machine information\n cpuCount: cpus.length,\n cpuModel: cpus.length ? cpus[0].model : null,\n cpuSpeed: cpus.length ? cpus[0].speed : null,\n memoryInMb: Math.trunc(os.totalmem() / Math.pow(1024, 2)),\n // Environment information\n isDocker: isDockerFunction(),\n isNowDev: NOW_REGION === 'dev1',\n isWsl: isWslBoolean,\n isCI: ciEnvironment.isCI,\n ciName: (ciEnvironment.isCI && ciEnvironment.name) || null,\n nextVersion: process.env.__NEXT_VERSION as string,\n agentName: await getAgentName(),\n }\n\n return traits\n}\n"],"names":["getAnonymousMeta","traits","cpus","os","NOW_REGION","process","env","systemPlatform","platform","systemRelease","release","systemArchitecture","arch","cpuCount","length","cpuModel","model","cpuSpeed","speed","memoryInMb","Math","trunc","totalmem","pow","isDocker","isDockerFunction","isNowDev","isWsl","isWslBoolean","isCI","ciEnvironment","ciName","name","nextVersion","__NEXT_VERSION","agentName","getAgentName"],"mappings":";;;;+BA0BsBA;;;eAAAA;;;iEA1BO;8DACJ;2DACV;gEAEgB;2BACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmB7B,IAAIC;AAEG,eAAeD;IACpB,IAAIC,QAAQ;QACV,OAAOA;IACT;IAEA,MAAMC,OAAOC,WAAE,CAACD,IAAI,MAAM,EAAE;IAC5B,MAAM,EAAEE,UAAU,EAAE,GAAGC,QAAQC,GAAG;IAClCL,SAAS;QACP,uBAAuB;QACvBM,gBAAgBJ,WAAE,CAACK,QAAQ;QAC3BC,eAAeN,WAAE,CAACO,OAAO;QACzBC,oBAAoBR,WAAE,CAACS,IAAI;QAC3B,sBAAsB;QACtBC,UAAUX,KAAKY,MAAM;QACrBC,UAAUb,KAAKY,MAAM,GAAGZ,IAAI,CAAC,EAAE,CAACc,KAAK,GAAG;QACxCC,UAAUf,KAAKY,MAAM,GAAGZ,IAAI,CAAC,EAAE,CAACgB,KAAK,GAAG;QACxCC,YAAYC,KAAKC,KAAK,CAAClB,WAAE,CAACmB,QAAQ,KAAKF,KAAKG,GAAG,CAAC,MAAM;QACtD,0BAA0B;QAC1BC,UAAUC,IAAAA,iBAAgB;QAC1BC,UAAUtB,eAAe;QACzBuB,OAAOC,cAAY;QACnBC,MAAMC,QAAcD,IAAI;QACxBE,QAAQ,AAACD,QAAcD,IAAI,IAAIC,QAAcE,IAAI,IAAK;QACtDC,aAAa5B,QAAQC,GAAG,CAAC4B,cAAc;QACvCC,WAAW,MAAMC,IAAAA,uBAAY;IAC/B;IAEA,OAAOnC;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/detached-flush.d.ts b/e-commerce/node_modules/next/dist/telemetry/detached-flush.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/detached-flush.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/detached-flush.js b/e-commerce/node_modules/next/dist/telemetry/detached-flush.js new file mode 100644 index 0000000000000000000000000000000000000000..272cf3abae70d0a376dd750fc9486e61db276233 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/detached-flush.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _storage = require("./storage"); +const _config = /*#__PURE__*/ _interop_require_default(require("../server/config")); +const _getprojectdir = require("../lib/get-project-dir"); +const _constants = require("../shared/lib/constants"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +(async ()=>{ + const [mode, inputDir, eventsFile, suppliedDistDir] = process.argv.slice(2); + let dir = inputDir; + if (!dir || mode !== 'dev') { + throw new Error(`Invalid flags should be run as node detached-flush dev ./path-to/project [eventsFile] [distDir]`); + } + dir = (0, _getprojectdir.getProjectDir)(dir); + // Build nudges pass their resolved output directory to avoid loading dev config again. + const distDir = suppliedDistDir ? _path.default.resolve(suppliedDistDir) : _path.default.join(dir, (await (0, _config.default)(_constants.PHASE_DEVELOPMENT_SERVER, dir)).distDir || '.next'); + // Named batches live in cache so build cleanup cannot remove them before submission. + // Retain the legacy root path for callers without an events filename. + const eventsPath = eventsFile && !eventsFile.includes('/') ? _path.default.join(distDir, 'cache', eventsFile) : _path.default.join(distDir, '_events.json'); + let events; + try { + events = JSON.parse(_fs.default.readFileSync(eventsPath, 'utf8')); + } catch (err) { + if (err.code === 'ENOENT') { + // no events to process we can exit now + process.exit(0); + } + throw err; + } + const telemetry = new _storage.Telemetry({ + distDir + }); + await telemetry.record(events); + await telemetry.flush(); + // finished flushing events clean-up + _fs.default.unlinkSync(eventsPath); +// Don't call process.exit() here - let Node.js exit naturally after +// all pending work completes (e.g., setTimeout in debug telemetry) +})(); + +//# sourceMappingURL=detached-flush.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/detached-flush.js.map b/e-commerce/node_modules/next/dist/telemetry/detached-flush.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2a7e7e3c675cab82d386041221a2dd79f49eb2e3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/detached-flush.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/detached-flush.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport type { TelemetryEvent } from './storage'\nimport { Telemetry } from './storage'\nimport loadConfig from '../server/config'\nimport { getProjectDir } from '../lib/get-project-dir'\nimport { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'\n\n// this process should be started with following arg order\n// 1. mode e.g. dev, export, start\n// 2. project dir\n// 3. events filename (optional, defaults to _events.json)\n// 4. resolved dist directory (optional, avoids reloading phase-specific config)\n;(async () => {\n const [mode, inputDir, eventsFile, suppliedDistDir] = process.argv.slice(2)\n let dir = inputDir\n\n if (!dir || mode !== 'dev') {\n throw new Error(\n `Invalid flags should be run as node detached-flush dev ./path-to/project [eventsFile] [distDir]`\n )\n }\n dir = getProjectDir(dir)\n\n // Build nudges pass their resolved output directory to avoid loading dev config again.\n const distDir = suppliedDistDir\n ? path.resolve(suppliedDistDir)\n : path.join(\n dir,\n (await loadConfig(PHASE_DEVELOPMENT_SERVER, dir)).distDir || '.next'\n )\n\n // Named batches live in cache so build cleanup cannot remove them before submission.\n // Retain the legacy root path for callers without an events filename.\n const eventsPath =\n eventsFile && !eventsFile.includes('/')\n ? path.join(distDir, 'cache', eventsFile)\n : path.join(distDir, '_events.json')\n\n let events: TelemetryEvent[]\n try {\n events = JSON.parse(fs.readFileSync(eventsPath, 'utf8'))\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n // no events to process we can exit now\n process.exit(0)\n }\n throw err\n }\n\n const telemetry = new Telemetry({ distDir })\n await telemetry.record(events)\n await telemetry.flush()\n\n // finished flushing events clean-up\n fs.unlinkSync(eventsPath)\n // Don't call process.exit() here - let Node.js exit naturally after\n // all pending work completes (e.g., setTimeout in debug telemetry)\n})()\n"],"names":["mode","inputDir","eventsFile","suppliedDistDir","process","argv","slice","dir","Error","getProjectDir","distDir","path","resolve","join","loadConfig","PHASE_DEVELOPMENT_SERVER","eventsPath","includes","events","JSON","parse","fs","readFileSync","err","code","exit","telemetry","Telemetry","record","flush","unlinkSync"],"mappings":";;;;2DAAe;6DACE;yBAES;+DACH;+BACO;2BACW;;;;;;AAOvC,CAAA;IACA,MAAM,CAACA,MAAMC,UAAUC,YAAYC,gBAAgB,GAAGC,QAAQC,IAAI,CAACC,KAAK,CAAC;IACzE,IAAIC,MAAMN;IAEV,IAAI,CAACM,OAAOP,SAAS,OAAO;QAC1B,MAAM,IAAIQ,MACR,CAAC,+FAA+F,CAAC;IAErG;IACAD,MAAME,IAAAA,4BAAa,EAACF;IAEpB,uFAAuF;IACvF,MAAMG,UAAUP,kBACZQ,aAAI,CAACC,OAAO,CAACT,mBACbQ,aAAI,CAACE,IAAI,CACPN,KACA,AAAC,CAAA,MAAMO,IAAAA,eAAU,EAACC,mCAAwB,EAAER,IAAG,EAAGG,OAAO,IAAI;IAGnE,qFAAqF;IACrF,sEAAsE;IACtE,MAAMM,aACJd,cAAc,CAACA,WAAWe,QAAQ,CAAC,OAC/BN,aAAI,CAACE,IAAI,CAACH,SAAS,SAASR,cAC5BS,aAAI,CAACE,IAAI,CAACH,SAAS;IAEzB,IAAIQ;IACJ,IAAI;QACFA,SAASC,KAAKC,KAAK,CAACC,WAAE,CAACC,YAAY,CAACN,YAAY;IAClD,EAAE,OAAOO,KAAU;QACjB,IAAIA,IAAIC,IAAI,KAAK,UAAU;YACzB,uCAAuC;YACvCpB,QAAQqB,IAAI,CAAC;QACf;QACA,MAAMF;IACR;IAEA,MAAMG,YAAY,IAAIC,kBAAS,CAAC;QAAEjB;IAAQ;IAC1C,MAAMgB,UAAUE,MAAM,CAACV;IACvB,MAAMQ,UAAUG,KAAK;IAErB,oCAAoC;IACpCR,WAAE,CAACS,UAAU,CAACd;AACd,oEAAoE;AACpE,mEAAmE;AACrE,CAAA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4831f258ae1de16eb77eed1139af206a3f3497f3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.d.ts @@ -0,0 +1,100 @@ +export type AgentUpgradePolicy = 'security' | 'latest' | 'experimental-future'; +export type AgentUpgradeOrigin = 'human_manual' | 'human_nudge' | 'agent_manual' | 'agent_nudge'; +export type AgentUpgradeHandoffMethod = 'existing_agent' | 'launched_agent' | 'copied_prompt' | 'printed_prompt'; +export type AgentUpgradeCLIResult = 'no_update_needed' | 'no_safe_target' | 'metadata_failure' | 'guide_failure' | 'cancelled' | 'handoff_issued' | 'handoff_failed' | 'cli_failure'; +export declare function eventAgentUpgradePolicyDetected(fields: { + configuredPolicy: AgentUpgradePolicy | false | null; + effectivePolicy: AgentUpgradePolicy; + policySource: 'config' | 'environment'; + sourceCommand: 'dev' | 'build'; +}): { + eventName: string; + payload: { + schemaVersion: number; + } & { + configuredPolicy: AgentUpgradePolicy | false | null; + effectivePolicy: AgentUpgradePolicy; + policySource: "config" | "environment"; + sourceCommand: "dev" | "build"; + }; +}; +export declare function eventAgentUpgradeNudgeShown(fields: { + nudgeId: string; + recipient: 'human' | 'agent'; + agentProduct: string | null; + sourceCommand: 'dev' | 'build'; + policy: AgentUpgradePolicy; + nudgeKind: AgentUpgradePolicy; +}): { + eventName: string; + payload: { + schemaVersion: number; + } & { + nudgeId: string; + recipient: "human" | "agent"; + agentProduct: string | null; + sourceCommand: "dev" | "build"; + policy: AgentUpgradePolicy; + nudgeKind: AgentUpgradePolicy; + }; +}; +export declare function eventAgentUpgradeNudgeDecision(fields: { + nudgeId: string; + action: 'update' | 'skip' | 'dismiss' | 'interrupt'; +}): { + eventName: string; + payload: { + schemaVersion: number; + } & { + nudgeId: string; + action: "update" | "skip" | "dismiss" | "interrupt"; + }; +}; +export declare function eventAgentUpgradeRunStarted(fields: { + runId: string; + nudgeId: string | null; + origin: AgentUpgradeOrigin; + agentProduct: string | null; + requestedPolicy: AgentUpgradePolicy | null; +}): { + eventName: string; + payload: { + schemaVersion: number; + } & { + runId: string; + nudgeId: string | null; + origin: AgentUpgradeOrigin; + agentProduct: string | null; + requestedPolicy: AgentUpgradePolicy | null; + }; +}; +export declare function eventAgentUpgradeCLIResult(fields: { + runId: string; + result: AgentUpgradeCLIResult; + resolvedPolicy: AgentUpgradePolicy | null; + handoffMethod: AgentUpgradeHandoffMethod | null; + selectedAgentProduct: string | null; +}): { + eventName: string; + payload: { + schemaVersion: number; + } & { + runId: string; + result: AgentUpgradeCLIResult; + resolvedPolicy: AgentUpgradePolicy | null; + handoffMethod: AgentUpgradeHandoffMethod | null; + selectedAgentProduct: string | null; + }; +}; +export declare function eventAgentUpgradeAgentResult(fields: { + runId: string; + result: 'success' | 'failure'; +}): { + eventName: string; + payload: { + schemaVersion: number; + } & { + runId: string; + result: "success" | "failure"; + }; +}; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.js b/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.js new file mode 100644 index 0000000000000000000000000000000000000000..a09814d4bbaaf87809650668914299741b905c77 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.js @@ -0,0 +1,69 @@ +// Shared values keep event payloads consistent across the CLI, nudges, and handoffs. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + eventAgentUpgradeAgentResult: null, + eventAgentUpgradeCLIResult: null, + eventAgentUpgradeNudgeDecision: null, + eventAgentUpgradeNudgeShown: null, + eventAgentUpgradePolicyDetected: null, + eventAgentUpgradeRunStarted: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + eventAgentUpgradeAgentResult: function() { + return eventAgentUpgradeAgentResult; + }, + eventAgentUpgradeCLIResult: function() { + return eventAgentUpgradeCLIResult; + }, + eventAgentUpgradeNudgeDecision: function() { + return eventAgentUpgradeNudgeDecision; + }, + eventAgentUpgradeNudgeShown: function() { + return eventAgentUpgradeNudgeShown; + }, + eventAgentUpgradePolicyDetected: function() { + return eventAgentUpgradePolicyDetected; + }, + eventAgentUpgradeRunStarted: function() { + return eventAgentUpgradeRunStarted; + } +}); +// Version every event so consumers can distinguish future schema changes. +function event(eventName, fields) { + return { + eventName, + payload: { + schemaVersion: 1, + ...fields + } + }; +} +function eventAgentUpgradePolicyDetected(fields) { + return event('NEXT_AGENT_UPGRADE_POLICY_DETECTED', fields); +} +function eventAgentUpgradeNudgeShown(fields) { + return event('NEXT_AGENT_UPGRADE_NUDGE_SHOWN', fields); +} +function eventAgentUpgradeNudgeDecision(fields) { + return event('NEXT_AGENT_UPGRADE_NUDGE_DECISION', fields); +} +function eventAgentUpgradeRunStarted(fields) { + return event('NEXT_AGENT_UPGRADE_RUN_STARTED', fields); +} +function eventAgentUpgradeCLIResult(fields) { + return event('NEXT_AGENT_UPGRADE_CLI_RESULT', fields); +} +function eventAgentUpgradeAgentResult(fields) { + return event('NEXT_AGENT_UPGRADE_AGENT_RESULT', fields); +} + +//# sourceMappingURL=agent-upgrade.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.js.map b/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.js.map new file mode 100644 index 0000000000000000000000000000000000000000..88cc4f4a088cdc23bbed8b1d0ecf78400ffa9155 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/agent-upgrade.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/agent-upgrade.ts"],"sourcesContent":["// Shared values keep event payloads consistent across the CLI, nudges, and handoffs.\nexport type AgentUpgradePolicy = 'security' | 'latest' | 'experimental-future'\n\nexport type AgentUpgradeOrigin =\n | 'human_manual'\n | 'human_nudge'\n | 'agent_manual'\n | 'agent_nudge'\n\nexport type AgentUpgradeHandoffMethod =\n | 'existing_agent'\n | 'launched_agent'\n | 'copied_prompt'\n | 'printed_prompt'\n\nexport type AgentUpgradeCLIResult =\n | 'no_update_needed'\n | 'no_safe_target'\n | 'metadata_failure'\n | 'guide_failure'\n | 'cancelled'\n | 'handoff_issued'\n | 'handoff_failed'\n | 'cli_failure'\n\n// Version every event so consumers can distinguish future schema changes.\nfunction event(eventName: string, fields: T) {\n return { eventName, payload: { schemaVersion: 1, ...fields } }\n}\n\n// Measure configured reach separately from whether an upgrade reminder is needed.\nexport function eventAgentUpgradePolicyDetected(fields: {\n configuredPolicy: AgentUpgradePolicy | false | null\n effectivePolicy: AgentUpgradePolicy\n policySource: 'config' | 'environment'\n sourceCommand: 'dev' | 'build'\n}) {\n return event('NEXT_AGENT_UPGRADE_POLICY_DETECTED', fields)\n}\n\n// Correlate a displayed reminder with a later upgrade invocation.\nexport function eventAgentUpgradeNudgeShown(fields: {\n nudgeId: string\n recipient: 'human' | 'agent'\n agentProduct: string | null\n sourceCommand: 'dev' | 'build'\n policy: AgentUpgradePolicy\n nudgeKind: AgentUpgradePolicy\n}) {\n return event('NEXT_AGENT_UPGRADE_NUDGE_SHOWN', fields)\n}\n\n// Human menus expose a decision directly; agent decisions are inferred from runs.\nexport function eventAgentUpgradeNudgeDecision(fields: {\n nudgeId: string\n action: 'update' | 'skip' | 'dismiss' | 'interrupt'\n}) {\n return event('NEXT_AGENT_UPGRADE_NUDGE_DECISION', fields)\n}\n\n// Count invocations independently of whether preparation or handoff finishes.\nexport function eventAgentUpgradeRunStarted(fields: {\n runId: string\n nudgeId: string | null\n origin: AgentUpgradeOrigin\n agentProduct: string | null\n requestedPolicy: AgentUpgradePolicy | null\n}) {\n return event('NEXT_AGENT_UPGRADE_RUN_STARTED', fields)\n}\n\n// Report the CLI's preparation and prompt delivery, not completion of the agent's work.\nexport function eventAgentUpgradeCLIResult(fields: {\n runId: string\n result: AgentUpgradeCLIResult\n resolvedPolicy: AgentUpgradePolicy | null\n handoffMethod: AgentUpgradeHandoffMethod | null\n selectedAgentProduct: string | null\n}) {\n return event('NEXT_AGENT_UPGRADE_CLI_RESULT', fields)\n}\n\n// The agent reports its verified result separately from the CLI's prompt delivery.\nexport function eventAgentUpgradeAgentResult(fields: {\n runId: string\n result: 'success' | 'failure'\n}) {\n return event('NEXT_AGENT_UPGRADE_AGENT_RESULT', fields)\n}\n"],"names":["eventAgentUpgradeAgentResult","eventAgentUpgradeCLIResult","eventAgentUpgradeNudgeDecision","eventAgentUpgradeNudgeShown","eventAgentUpgradePolicyDetected","eventAgentUpgradeRunStarted","event","eventName","fields","payload","schemaVersion"],"mappings":"AAAA,qFAAqF;;;;;;;;;;;;;;;;;;;;IAmFrEA,4BAA4B;eAA5BA;;IAXAC,0BAA0B;eAA1BA;;IAnBAC,8BAA8B;eAA9BA;;IAZAC,2BAA2B;eAA3BA;;IAVAC,+BAA+B;eAA/BA;;IA8BAC,2BAA2B;eAA3BA;;;AApChB,0EAA0E;AAC1E,SAASC,MAAwBC,SAAiB,EAAEC,MAAS;IAC3D,OAAO;QAAED;QAAWE,SAAS;YAAEC,eAAe;YAAG,GAAGF,MAAM;QAAC;IAAE;AAC/D;AAGO,SAASJ,gCAAgCI,MAK/C;IACC,OAAOF,MAAM,sCAAsCE;AACrD;AAGO,SAASL,4BAA4BK,MAO3C;IACC,OAAOF,MAAM,kCAAkCE;AACjD;AAGO,SAASN,+BAA+BM,MAG9C;IACC,OAAOF,MAAM,qCAAqCE;AACpD;AAGO,SAASH,4BAA4BG,MAM3C;IACC,OAAOF,MAAM,kCAAkCE;AACjD;AAGO,SAASP,2BAA2BO,MAM1C;IACC,OAAOF,MAAM,iCAAiCE;AAChD;AAGO,SAASR,6BAA6BQ,MAG5C;IACC,OAAOF,MAAM,mCAAmCE;AAClD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/build.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/build.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27948f70eedbf8d4390df615166f8e2529756083 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/build.d.ts @@ -0,0 +1,145 @@ +import type { TelemetryPlugin } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'; +import type { SWC_TARGET_TRIPLE } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'; +import type { UseCacheTrackerKey } from '../../build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils'; +type EventTypeCheckCompleted = { + durationInSeconds: number; + typescriptVersion: string | null; + inputFilesCount?: number; + totalFilesCount?: number; + incremental?: boolean; + typeCheckMode: 'typescript-api' | 'typescript-cli'; +}; +export declare function eventTypeCheckCompleted(event: EventTypeCheckCompleted): { + eventName: string; + payload: EventTypeCheckCompleted; +}; +export type EventLintCheckCompleted = { + durationInSeconds: number; + eslintVersion: string | null; + lintedFilesCount?: number; + lintFix?: boolean; + buildLint?: boolean; + nextEslintPluginVersion?: string | null; + nextEslintPluginErrorsCount?: number; + nextEslintPluginWarningsCount?: number; + nextRulesEnabled: { + [ruleName: `@next/next/${string}`]: 'off' | 'warn' | 'error'; + }; +}; +export declare function eventLintCheckCompleted(event: EventLintCheckCompleted): { + eventName: string; + payload: EventLintCheckCompleted; +}; +type AnalyzeEventCompleted = { + durationInSeconds: number; + success: true; + totalPageCount: number; +} | { + success: false; +}; +export declare function eventAnalyzeCompleted(event: AnalyzeEventCompleted): { + eventName: string; + payload: AnalyzeEventCompleted; +}; +type EventBuildCompleted = { + bundler: 'webpack' | 'rspack' | 'turbopack'; + durationInSeconds: number; + totalPageCount: number; + hasDunderPages: boolean; + hasTestPages: boolean; + totalAppPagesCount?: number; +}; +export declare function eventBuildCompleted(pagePaths: string[], event: Omit): { + eventName: string; + payload: EventBuildCompleted; +}; +type EventBuildFailed = { + bundler: 'webpack' | 'rspack' | 'turbopack'; + errorCode: string; + durationInSeconds: number; +}; +export declare function eventBuildFailed(event: EventBuildFailed): { + eventName: string; + payload: EventBuildFailed; +}; +type EventBuildOptimized = { + durationInSeconds: number; + totalPageCount: number; + staticPageCount: number; + staticPropsPageCount: number; + serverPropsPageCount: number; + ssrPageCount: number; + hasDunderPages: boolean; + hasTestPages: boolean; + hasStatic404: boolean; + hasReportWebVitals: boolean; + headersCount: number; + rewritesCount: number; + redirectsCount: number; + headersWithHasCount: number; + rewritesWithHasCount: number; + redirectsWithHasCount: number; + middlewareCount: number; + isRspack: boolean; + totalAppPagesCount?: number; + staticAppPagesCount?: number; + serverAppPagesCount?: number; + edgeRuntimeAppCount?: number; + edgeRuntimePagesCount?: number; +}; +export declare function eventBuildOptimize(pagePaths: string[], event: Omit): { + eventName: string; + payload: EventBuildOptimized; +}; +export declare const EVENT_BUILD_FEATURE_USAGE = "NEXT_BUILD_FEATURE_USAGE"; +export type EventBuildFeatureUsage = { + featureName: 'next/image' | 'next/legacy/image' | 'next/future/image' | 'next/script' | 'next/dynamic' | '@next/font/google' | '@next/font/local' | 'next/font/google' | 'next/font/local' | 'experimental/nextScriptWorkers' | 'experimental/cacheComponents' | 'experimental/optimizeCss' | 'swcLoader' | 'swcRelay' | 'swcStyledComponents' | 'swcReactRemoveProperties' | 'swcExperimentalDecorators' | 'swcRemoveConsole' | 'swcImportSource' | 'swcEmotion' | `swc/target/${SWC_TARGET_TRIPLE}` | 'turbotrace' | 'vercelImageGeneration' | 'transpilePackages' | 'skipProxyUrlNormalize' | 'skipTrailingSlashRedirect' | 'modularizeImports' | 'esmExternals' | 'webpackPlugins' | UseCacheTrackerKey | 'turbopackFileSystemCache' | 'runAfterProductionCompile'; + invocationCount: number; +}; +export declare function eventBuildFeatureUsage(usages: ReturnType): Array<{ + eventName: string; + payload: EventBuildFeatureUsage; +}>; +/** + * Converts aggregated Turbopack feature-usage diagnostics (emitted by the + * Rust side from `FeatureUsageTelemetry` and aggregated per-feature by + * `get_diagnostics`) into `EVENT_BUILD_FEATURE_USAGE` telemetry events. + */ +export declare function eventBuildFeatureUsageFromTurbopack(diagnostics: ReadonlyArray<{ + featureName: string; + invocationCount: number; +}>): Array<{ + eventName: string; + payload: EventBuildFeatureUsage; +}>; +export declare const EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS = "NEXT_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS"; +export type EventPackageUsedInGetServerSideProps = { + package: string; +}; +export declare function eventPackageUsedInGetServerSideProps(packagesUsedInServerSideProps: ReturnType): Array<{ + eventName: string; + payload: EventPackageUsedInGetServerSideProps; +}>; +export declare const EVENT_MCP_TOOL_USAGE = "NEXT_MCP_TOOL_USAGE"; +export type McpToolName = 'mcp/get_errors' | 'mcp/get_logs' | 'mcp/get_page_metadata' | 'mcp/get_project_metadata' | 'mcp/get_routes' | 'mcp/get_request_insights' | 'mcp/get_server_action_by_id' | 'mcp/get_compilation_issues' | 'mcp/compile_route'; +export type EventMcpToolUsage = { + toolName: McpToolName; + invocationCount: number; +}; +export declare function eventMcpToolUsage(usages: Array<{ + featureName: McpToolName; + invocationCount: number; +}>): Array<{ + eventName: string; + payload: EventMcpToolUsage; +}>; +export declare const ERROR_THROWN_EVENT = "NEXT_ERROR_THROWN"; +type ErrorThrownEvent = { + eventName: typeof ERROR_THROWN_EVENT; + payload: { + errorCode: string | undefined; + location: string | undefined; + }; +}; +export declare function eventErrorThrown(error: Error, anonymizedLocation: string | undefined): ErrorThrownEvent; +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/build.js b/e-commerce/node_modules/next/dist/telemetry/events/build.js new file mode 100644 index 0000000000000000000000000000000000000000..59b031e3e0d05d6b126d673993a47c6542c9b589 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/build.js @@ -0,0 +1,186 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ERROR_THROWN_EVENT: null, + EVENT_BUILD_FEATURE_USAGE: null, + EVENT_MCP_TOOL_USAGE: null, + EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS: null, + eventAnalyzeCompleted: null, + eventBuildCompleted: null, + eventBuildFailed: null, + eventBuildFeatureUsage: null, + eventBuildFeatureUsageFromTurbopack: null, + eventBuildOptimize: null, + eventErrorThrown: null, + eventLintCheckCompleted: null, + eventMcpToolUsage: null, + eventPackageUsedInGetServerSideProps: null, + eventTypeCheckCompleted: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ERROR_THROWN_EVENT: function() { + return ERROR_THROWN_EVENT; + }, + EVENT_BUILD_FEATURE_USAGE: function() { + return EVENT_BUILD_FEATURE_USAGE; + }, + EVENT_MCP_TOOL_USAGE: function() { + return EVENT_MCP_TOOL_USAGE; + }, + EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS: function() { + return EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS; + }, + eventAnalyzeCompleted: function() { + return eventAnalyzeCompleted; + }, + eventBuildCompleted: function() { + return eventBuildCompleted; + }, + eventBuildFailed: function() { + return eventBuildFailed; + }, + eventBuildFeatureUsage: function() { + return eventBuildFeatureUsage; + }, + eventBuildFeatureUsageFromTurbopack: function() { + return eventBuildFeatureUsageFromTurbopack; + }, + eventBuildOptimize: function() { + return eventBuildOptimize; + }, + eventErrorThrown: function() { + return eventErrorThrown; + }, + eventLintCheckCompleted: function() { + return eventLintCheckCompleted; + }, + eventMcpToolUsage: function() { + return eventMcpToolUsage; + }, + eventPackageUsedInGetServerSideProps: function() { + return eventPackageUsedInGetServerSideProps; + }, + eventTypeCheckCompleted: function() { + return eventTypeCheckCompleted; + } +}); +const REGEXP_DIRECTORY_DUNDER = /[\\/]__[^\\/]+(?REGEXP_DIRECTORY_DUNDER.test(path)), + hasTestPages: pagePaths.some((path)=>REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)), + totalAppPagesCount: event.totalAppPagesCount + } + }; +} +const EVENT_BUILD_FAILED = 'NEXT_BUILD_FAILED'; +function eventBuildFailed(event) { + return { + eventName: EVENT_BUILD_FAILED, + payload: event + }; +} +const EVENT_BUILD_OPTIMIZED = 'NEXT_BUILD_OPTIMIZED'; +function eventBuildOptimize(pagePaths, event) { + return { + eventName: EVENT_BUILD_OPTIMIZED, + payload: { + ...event, + totalPageCount: pagePaths.length, + hasDunderPages: pagePaths.some((path)=>REGEXP_DIRECTORY_DUNDER.test(path)), + hasTestPages: pagePaths.some((path)=>REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)), + totalAppPagesCount: event.totalAppPagesCount, + staticAppPagesCount: event.staticAppPagesCount, + serverAppPagesCount: event.serverAppPagesCount, + edgeRuntimeAppCount: event.edgeRuntimeAppCount, + edgeRuntimePagesCount: event.edgeRuntimePagesCount, + isRspack: process.env.NEXT_RSPACK !== undefined + } + }; +} +const EVENT_BUILD_FEATURE_USAGE = 'NEXT_BUILD_FEATURE_USAGE'; +function eventBuildFeatureUsage(usages) { + return usages.map(({ featureName, invocationCount })=>({ + eventName: EVENT_BUILD_FEATURE_USAGE, + payload: { + featureName, + invocationCount + } + })); +} +function eventBuildFeatureUsageFromTurbopack(diagnostics) { + return diagnostics.map(({ featureName, invocationCount })=>({ + eventName: EVENT_BUILD_FEATURE_USAGE, + payload: { + featureName: featureName, + invocationCount + } + })); +} +const EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS = 'NEXT_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS'; +function eventPackageUsedInGetServerSideProps(packagesUsedInServerSideProps) { + return packagesUsedInServerSideProps.map((packageName)=>({ + eventName: EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS, + payload: { + package: packageName + } + })); +} +const EVENT_MCP_TOOL_USAGE = 'NEXT_MCP_TOOL_USAGE'; +function eventMcpToolUsage(usages) { + return usages.map(({ featureName, invocationCount })=>({ + eventName: EVENT_MCP_TOOL_USAGE, + payload: { + toolName: featureName, + invocationCount + } + })); +} +const ERROR_THROWN_EVENT = 'NEXT_ERROR_THROWN'; +function eventErrorThrown(error, anonymizedLocation) { + return { + eventName: ERROR_THROWN_EVENT, + payload: { + errorCode: error.name || 'Unknown', + location: anonymizedLocation + } + }; +} + +//# sourceMappingURL=build.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/build.js.map b/e-commerce/node_modules/next/dist/telemetry/events/build.js.map new file mode 100644 index 0000000000000000000000000000000000000000..319820ffd812eaea313f22ecde84e7e90d2ca827 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/build.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/build.ts"],"sourcesContent":["import type { TelemetryPlugin } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'\nimport type { SWC_TARGET_TRIPLE } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'\nimport type { UseCacheTrackerKey } from '../../build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils'\n\nconst REGEXP_DIRECTORY_DUNDER =\n /[\\\\/]__[^\\\\/]+(?\n): { eventName: string; payload: EventBuildCompleted } {\n return {\n eventName: EVENT_BUILD_COMPLETED,\n payload: {\n ...event,\n totalPageCount: pagePaths.length,\n hasDunderPages: pagePaths.some((path) =>\n REGEXP_DIRECTORY_DUNDER.test(path)\n ),\n hasTestPages: pagePaths.some(\n (path) =>\n REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)\n ),\n totalAppPagesCount: event.totalAppPagesCount,\n },\n }\n}\n\nconst EVENT_BUILD_FAILED = 'NEXT_BUILD_FAILED'\ntype EventBuildFailed = {\n bundler: 'webpack' | 'rspack' | 'turbopack'\n errorCode: string\n durationInSeconds: number\n}\n\nexport function eventBuildFailed(event: EventBuildFailed) {\n return {\n eventName: EVENT_BUILD_FAILED,\n payload: event,\n }\n}\n\nconst EVENT_BUILD_OPTIMIZED = 'NEXT_BUILD_OPTIMIZED'\ntype EventBuildOptimized = {\n durationInSeconds: number\n totalPageCount: number\n staticPageCount: number\n staticPropsPageCount: number\n serverPropsPageCount: number\n ssrPageCount: number\n hasDunderPages: boolean\n hasTestPages: boolean\n hasStatic404: boolean\n hasReportWebVitals: boolean\n headersCount: number\n rewritesCount: number\n redirectsCount: number\n headersWithHasCount: number\n rewritesWithHasCount: number\n redirectsWithHasCount: number\n middlewareCount: number\n isRspack: boolean\n totalAppPagesCount?: number\n staticAppPagesCount?: number\n serverAppPagesCount?: number\n edgeRuntimeAppCount?: number\n edgeRuntimePagesCount?: number\n}\n\nexport function eventBuildOptimize(\n pagePaths: string[],\n event: Omit<\n EventBuildOptimized,\n 'totalPageCount' | 'hasDunderPages' | 'hasTestPages' | 'isRspack'\n >\n): { eventName: string; payload: EventBuildOptimized } {\n return {\n eventName: EVENT_BUILD_OPTIMIZED,\n payload: {\n ...event,\n totalPageCount: pagePaths.length,\n hasDunderPages: pagePaths.some((path) =>\n REGEXP_DIRECTORY_DUNDER.test(path)\n ),\n hasTestPages: pagePaths.some(\n (path) =>\n REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)\n ),\n totalAppPagesCount: event.totalAppPagesCount,\n staticAppPagesCount: event.staticAppPagesCount,\n serverAppPagesCount: event.serverAppPagesCount,\n edgeRuntimeAppCount: event.edgeRuntimeAppCount,\n edgeRuntimePagesCount: event.edgeRuntimePagesCount,\n isRspack: process.env.NEXT_RSPACK !== undefined,\n },\n }\n}\n\nexport const EVENT_BUILD_FEATURE_USAGE = 'NEXT_BUILD_FEATURE_USAGE'\nexport type EventBuildFeatureUsage = {\n // NOTE: If you are adding features, make sure to update the `enum` field\n // for `featureName` in https://github.com/vercel/next-telemetry/blob/master/events/v1/featureUsage.ts\n // *before* you make changes here.\n featureName:\n | 'next/image'\n | 'next/legacy/image'\n | 'next/future/image'\n | 'next/script'\n | 'next/dynamic'\n | '@next/font/google'\n | '@next/font/local'\n | 'next/font/google'\n | 'next/font/local'\n | 'experimental/nextScriptWorkers'\n | 'experimental/cacheComponents'\n | 'experimental/optimizeCss'\n | 'swcLoader'\n | 'swcRelay'\n | 'swcStyledComponents'\n | 'swcReactRemoveProperties'\n | 'swcExperimentalDecorators'\n | 'swcRemoveConsole'\n | 'swcImportSource'\n | 'swcEmotion'\n | `swc/target/${SWC_TARGET_TRIPLE}`\n | 'turbotrace'\n | 'vercelImageGeneration'\n | 'transpilePackages'\n | 'skipProxyUrlNormalize'\n | 'skipTrailingSlashRedirect'\n | 'modularizeImports'\n | 'esmExternals'\n | 'webpackPlugins'\n | UseCacheTrackerKey\n | 'turbopackFileSystemCache'\n | 'runAfterProductionCompile'\n invocationCount: number\n}\nexport function eventBuildFeatureUsage(\n usages: ReturnType\n): Array<{ eventName: string; payload: EventBuildFeatureUsage }> {\n return usages.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: {\n featureName,\n invocationCount,\n },\n }))\n}\n\n/**\n * Converts aggregated Turbopack feature-usage diagnostics (emitted by the\n * Rust side from `FeatureUsageTelemetry` and aggregated per-feature by\n * `get_diagnostics`) into `EVENT_BUILD_FEATURE_USAGE` telemetry events.\n */\nexport function eventBuildFeatureUsageFromTurbopack(\n diagnostics: ReadonlyArray<{\n featureName: string\n invocationCount: number\n }>\n): Array<{ eventName: string; payload: EventBuildFeatureUsage }> {\n return diagnostics.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: {\n featureName: featureName as EventBuildFeatureUsage['featureName'],\n invocationCount,\n },\n }))\n}\n\nexport const EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS =\n 'NEXT_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS'\n\nexport type EventPackageUsedInGetServerSideProps = {\n package: string\n}\n\nexport function eventPackageUsedInGetServerSideProps(\n packagesUsedInServerSideProps: ReturnType<\n TelemetryPlugin['packagesUsedInServerSideProps']\n >\n): Array<{ eventName: string; payload: EventPackageUsedInGetServerSideProps }> {\n return packagesUsedInServerSideProps.map((packageName) => ({\n eventName: EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS,\n payload: {\n package: packageName,\n },\n }))\n}\n\nexport const EVENT_MCP_TOOL_USAGE = 'NEXT_MCP_TOOL_USAGE'\n\nexport type McpToolName =\n | 'mcp/get_errors'\n | 'mcp/get_logs'\n | 'mcp/get_page_metadata'\n | 'mcp/get_project_metadata'\n | 'mcp/get_routes'\n | 'mcp/get_request_insights'\n | 'mcp/get_server_action_by_id'\n | 'mcp/get_compilation_issues'\n | 'mcp/compile_route'\n\nexport type EventMcpToolUsage = {\n toolName: McpToolName\n invocationCount: number\n}\n\nexport function eventMcpToolUsage(\n usages: Array<{ featureName: McpToolName; invocationCount: number }>\n): Array<{ eventName: string; payload: EventMcpToolUsage }> {\n return usages.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_MCP_TOOL_USAGE,\n payload: {\n toolName: featureName,\n invocationCount,\n },\n }))\n}\n\nexport const ERROR_THROWN_EVENT = 'NEXT_ERROR_THROWN'\ntype ErrorThrownEvent = {\n eventName: typeof ERROR_THROWN_EVENT\n payload: {\n errorCode: string | undefined\n location: string | undefined\n }\n}\n\n// Creates a Telemetry event for errors. For privacy, only includes the error name and not the error\n// message. The payload field retains its existing name for telemetry schema compatibility.\n//\n// `location` may be included if it's a location internal to the next.js source tree (i.e. a\n// non-absolute path).\nexport function eventErrorThrown(\n error: Error,\n anonymizedLocation: string | undefined\n): ErrorThrownEvent {\n return {\n eventName: ERROR_THROWN_EVENT,\n payload: {\n errorCode: error.name || 'Unknown',\n location: anonymizedLocation,\n },\n }\n}\n"],"names":["ERROR_THROWN_EVENT","EVENT_BUILD_FEATURE_USAGE","EVENT_MCP_TOOL_USAGE","EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS","eventAnalyzeCompleted","eventBuildCompleted","eventBuildFailed","eventBuildFeatureUsage","eventBuildFeatureUsageFromTurbopack","eventBuildOptimize","eventErrorThrown","eventLintCheckCompleted","eventMcpToolUsage","eventPackageUsedInGetServerSideProps","eventTypeCheckCompleted","REGEXP_DIRECTORY_DUNDER","REGEXP_DIRECTORY_TESTS","REGEXP_FILE_TEST","EVENT_TYPE_CHECK_COMPLETED","event","eventName","payload","EVENT_LINT_CHECK_COMPLETED","EVENT_ANALYZE_COMPLETED","EVENT_BUILD_COMPLETED","pagePaths","totalPageCount","length","hasDunderPages","some","path","test","hasTestPages","totalAppPagesCount","EVENT_BUILD_FAILED","EVENT_BUILD_OPTIMIZED","staticAppPagesCount","serverAppPagesCount","edgeRuntimeAppCount","edgeRuntimePagesCount","isRspack","process","env","NEXT_RSPACK","undefined","usages","map","featureName","invocationCount","diagnostics","packagesUsedInServerSideProps","packageName","package","toolName","error","anonymizedLocation","errorCode","name","location"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6SaA,kBAAkB;eAAlBA;;IA1HAC,yBAAyB;eAAzBA;;IA4FAC,oBAAoB;eAApBA;;IApBAC,gDAAgD;eAAhDA;;IA1LGC,qBAAqB;eAArBA;;IAoBAC,mBAAmB;eAAnBA;;IA+BAC,gBAAgB;eAAhBA;;IAuGAC,sBAAsB;eAAtBA;;IAiBAC,mCAAmC;eAAnCA;;IAtFAC,kBAAkB;eAAlBA;;IAqKAC,gBAAgB;eAAhBA;;IA/QAC,uBAAuB;eAAvBA;;IAqPAC,iBAAiB;eAAjBA;;IA/BAC,oCAAoC;eAApCA;;IA/OAC,uBAAuB;eAAvBA;;;AAfhB,MAAMC,0BACJ;AACF,MAAMC,yBAAyB;AAC/B,MAAMC,mBAAmB;AAEzB,MAAMC,6BAA6B;AAU5B,SAASJ,wBAAwBK,KAA8B;IAIpE,OAAO;QACLC,WAAWF;QACXG,SAASF;IACX;AACF;AAEA,MAAMG,6BAA6B;AAe5B,SAASX,wBAAwBQ,KAA8B;IAIpE,OAAO;QACLC,WAAWE;QACXD,SAASF;IACX;AACF;AAEA,MAAMI,0BAA0B;AAWzB,SAASnB,sBAAsBe,KAA4B;IAIhE,OAAO;QACLC,WAAWG;QACXF,SAASF;IACX;AACF;AAEA,MAAMK,wBAAwB;AAUvB,SAASnB,oBACdoB,SAAmB,EACnBN,KAGC;IAED,OAAO;QACLC,WAAWI;QACXH,SAAS;YACP,GAAGF,KAAK;YACRO,gBAAgBD,UAAUE,MAAM;YAChCC,gBAAgBH,UAAUI,IAAI,CAAC,CAACC,OAC9Bf,wBAAwBgB,IAAI,CAACD;YAE/BE,cAAcP,UAAUI,IAAI,CAC1B,CAACC,OACCd,uBAAuBe,IAAI,CAACD,SAASb,iBAAiBc,IAAI,CAACD;YAE/DG,oBAAoBd,MAAMc,kBAAkB;QAC9C;IACF;AACF;AAEA,MAAMC,qBAAqB;AAOpB,SAAS5B,iBAAiBa,KAAuB;IACtD,OAAO;QACLC,WAAWc;QACXb,SAASF;IACX;AACF;AAEA,MAAMgB,wBAAwB;AA2BvB,SAAS1B,mBACdgB,SAAmB,EACnBN,KAGC;IAED,OAAO;QACLC,WAAWe;QACXd,SAAS;YACP,GAAGF,KAAK;YACRO,gBAAgBD,UAAUE,MAAM;YAChCC,gBAAgBH,UAAUI,IAAI,CAAC,CAACC,OAC9Bf,wBAAwBgB,IAAI,CAACD;YAE/BE,cAAcP,UAAUI,IAAI,CAC1B,CAACC,OACCd,uBAAuBe,IAAI,CAACD,SAASb,iBAAiBc,IAAI,CAACD;YAE/DG,oBAAoBd,MAAMc,kBAAkB;YAC5CG,qBAAqBjB,MAAMiB,mBAAmB;YAC9CC,qBAAqBlB,MAAMkB,mBAAmB;YAC9CC,qBAAqBnB,MAAMmB,mBAAmB;YAC9CC,uBAAuBpB,MAAMoB,qBAAqB;YAClDC,UAAUC,QAAQC,GAAG,CAACC,WAAW,KAAKC;QACxC;IACF;AACF;AAEO,MAAM3C,4BAA4B;AAwClC,SAASM,uBACdsC,MAA6C;IAE7C,OAAOA,OAAOC,GAAG,CAAC,CAAC,EAAEC,WAAW,EAAEC,eAAe,EAAE,GAAM,CAAA;YACvD5B,WAAWnB;YACXoB,SAAS;gBACP0B;gBACAC;YACF;QACF,CAAA;AACF;AAOO,SAASxC,oCACdyC,WAGE;IAEF,OAAOA,YAAYH,GAAG,CAAC,CAAC,EAAEC,WAAW,EAAEC,eAAe,EAAE,GAAM,CAAA;YAC5D5B,WAAWnB;YACXoB,SAAS;gBACP0B,aAAaA;gBACbC;YACF;QACF,CAAA;AACF;AAEO,MAAM7C,mDACX;AAMK,SAASU,qCACdqC,6BAEC;IAED,OAAOA,8BAA8BJ,GAAG,CAAC,CAACK,cAAiB,CAAA;YACzD/B,WAAWjB;YACXkB,SAAS;gBACP+B,SAASD;YACX;QACF,CAAA;AACF;AAEO,MAAMjD,uBAAuB;AAkB7B,SAASU,kBACdiC,MAAoE;IAEpE,OAAOA,OAAOC,GAAG,CAAC,CAAC,EAAEC,WAAW,EAAEC,eAAe,EAAE,GAAM,CAAA;YACvD5B,WAAWlB;YACXmB,SAAS;gBACPgC,UAAUN;gBACVC;YACF;QACF,CAAA;AACF;AAEO,MAAMhD,qBAAqB;AAc3B,SAASU,iBACd4C,KAAY,EACZC,kBAAsC;IAEtC,OAAO;QACLnC,WAAWpB;QACXqB,SAAS;YACPmC,WAAWF,MAAMG,IAAI,IAAI;YACzBC,UAAUH;QACZ;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/build.test.js b/e-commerce/node_modules/next/dist/telemetry/events/build.test.js new file mode 100644 index 0000000000000000000000000000000000000000..03be0637b5e3152b02e655bc0386d75ae4bb14ce --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/build.test.js @@ -0,0 +1,74 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _build = require("./build"); +describe('eventBuildFeatureUsageFromTurbopackDiagnostics', ()=>{ + it('returns empty for empty input', ()=>{ + expect((0, _build.eventBuildFeatureUsageFromTurbopack)([])).toEqual([]); + }); + it('maps a single diagnostic to one event', ()=>{ + const events = (0, _build.eventBuildFeatureUsageFromTurbopack)([ + { + featureName: 'next/image', + invocationCount: 3 + } + ]); + expect(events).toEqual([ + { + eventName: _build.EVENT_BUILD_FEATURE_USAGE, + payload: { + featureName: 'next/image', + invocationCount: 3 + } + } + ]); + }); + it('preserves invocationCount of 0 for disabled boolean flags', ()=>{ + const events = (0, _build.eventBuildFeatureUsageFromTurbopack)([ + { + featureName: 'swcRelay', + invocationCount: 0 + } + ]); + expect(events).toEqual([ + { + eventName: _build.EVENT_BUILD_FEATURE_USAGE, + payload: { + featureName: 'swcRelay', + invocationCount: 0 + } + } + ]); + }); + it('passes through multiple distinct diagnostics (already aggregated Rust-side)', ()=>{ + const events = (0, _build.eventBuildFeatureUsageFromTurbopack)([ + { + featureName: 'next/image', + invocationCount: 2 + }, + { + featureName: 'next/script', + invocationCount: 1 + } + ]); + expect(events).toEqual([ + { + eventName: _build.EVENT_BUILD_FEATURE_USAGE, + payload: { + featureName: 'next/image', + invocationCount: 2 + } + }, + { + eventName: _build.EVENT_BUILD_FEATURE_USAGE, + payload: { + featureName: 'next/script', + invocationCount: 1 + } + } + ]); + }); +}); + +//# sourceMappingURL=build.test.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/build.test.js.map b/e-commerce/node_modules/next/dist/telemetry/events/build.test.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6721527a39f6ad59f6f030dec81c9e254ff71cb3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/build.test.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/build.test.ts"],"sourcesContent":["import {\n EVENT_BUILD_FEATURE_USAGE,\n eventBuildFeatureUsageFromTurbopack,\n} from './build'\n\ndescribe('eventBuildFeatureUsageFromTurbopackDiagnostics', () => {\n it('returns empty for empty input', () => {\n expect(eventBuildFeatureUsageFromTurbopack([])).toEqual([])\n })\n\n it('maps a single diagnostic to one event', () => {\n const events = eventBuildFeatureUsageFromTurbopack([\n { featureName: 'next/image', invocationCount: 3 },\n ])\n expect(events).toEqual([\n {\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: { featureName: 'next/image', invocationCount: 3 },\n },\n ])\n })\n\n it('preserves invocationCount of 0 for disabled boolean flags', () => {\n const events = eventBuildFeatureUsageFromTurbopack([\n { featureName: 'swcRelay', invocationCount: 0 },\n ])\n expect(events).toEqual([\n {\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: { featureName: 'swcRelay', invocationCount: 0 },\n },\n ])\n })\n\n it('passes through multiple distinct diagnostics (already aggregated Rust-side)', () => {\n const events = eventBuildFeatureUsageFromTurbopack([\n { featureName: 'next/image', invocationCount: 2 },\n { featureName: 'next/script', invocationCount: 1 },\n ])\n expect(events).toEqual([\n {\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: { featureName: 'next/image', invocationCount: 2 },\n },\n {\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: { featureName: 'next/script', invocationCount: 1 },\n },\n ])\n })\n})\n"],"names":["describe","it","expect","eventBuildFeatureUsageFromTurbopack","toEqual","events","featureName","invocationCount","eventName","EVENT_BUILD_FEATURE_USAGE","payload"],"mappings":";;;;uBAGO;AAEPA,SAAS,kDAAkD;IACzDC,GAAG,iCAAiC;QAClCC,OAAOC,IAAAA,0CAAmC,EAAC,EAAE,GAAGC,OAAO,CAAC,EAAE;IAC5D;IAEAH,GAAG,yCAAyC;QAC1C,MAAMI,SAASF,IAAAA,0CAAmC,EAAC;YACjD;gBAAEG,aAAa;gBAAcC,iBAAiB;YAAE;SACjD;QACDL,OAAOG,QAAQD,OAAO,CAAC;YACrB;gBACEI,WAAWC,gCAAyB;gBACpCC,SAAS;oBAAEJ,aAAa;oBAAcC,iBAAiB;gBAAE;YAC3D;SACD;IACH;IAEAN,GAAG,6DAA6D;QAC9D,MAAMI,SAASF,IAAAA,0CAAmC,EAAC;YACjD;gBAAEG,aAAa;gBAAYC,iBAAiB;YAAE;SAC/C;QACDL,OAAOG,QAAQD,OAAO,CAAC;YACrB;gBACEI,WAAWC,gCAAyB;gBACpCC,SAAS;oBAAEJ,aAAa;oBAAYC,iBAAiB;gBAAE;YACzD;SACD;IACH;IAEAN,GAAG,+EAA+E;QAChF,MAAMI,SAASF,IAAAA,0CAAmC,EAAC;YACjD;gBAAEG,aAAa;gBAAcC,iBAAiB;YAAE;YAChD;gBAAED,aAAa;gBAAeC,iBAAiB;YAAE;SAClD;QACDL,OAAOG,QAAQD,OAAO,CAAC;YACrB;gBACEI,WAAWC,gCAAyB;gBACpCC,SAAS;oBAAEJ,aAAa;oBAAcC,iBAAiB;gBAAE;YAC3D;YACA;gBACEC,WAAWC,gCAAyB;gBACpCC,SAAS;oBAAEJ,aAAa;oBAAeC,iBAAiB;gBAAE;YAC5D;SACD;IACH;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/index.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10954a674dd2a006529e14c25357f6d52a73dad3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/index.d.ts @@ -0,0 +1,5 @@ +export * from './version'; +export * from './build'; +export * from './plugins'; +export type { McpToolName, EventMcpToolUsage } from './build'; +export { EVENT_MCP_TOOL_USAGE, eventMcpToolUsage } from './build'; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/index.js b/e-commerce/node_modules/next/dist/telemetry/events/index.js new file mode 100644 index 0000000000000000000000000000000000000000..aa2ef706255f7ef075ed530728f72384fe5a646b --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/index.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + EVENT_MCP_TOOL_USAGE: null, + eventMcpToolUsage: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + EVENT_MCP_TOOL_USAGE: function() { + return _build.EVENT_MCP_TOOL_USAGE; + }, + eventMcpToolUsage: function() { + return _build.eventMcpToolUsage; + } +}); +0 && __export(require("./version")) && __export(require("./build")) && __export(require("./plugins")); +_export_star(require("./version"), exports); +const _build = _export_star(require("./build"), exports); +_export_star(require("./plugins"), exports); +function _export_star(from, to) { + Object.keys(from).forEach(function(k) { + if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { + Object.defineProperty(to, k, { + enumerable: true, + get: function() { + return from[k]; + } + }); + } + }); + return from; +} + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/index.js.map b/e-commerce/node_modules/next/dist/telemetry/events/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9b497c99d452c9fa07fdd131ec40a0eb8c7dbd90 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/index.ts"],"sourcesContent":["export * from './version'\nexport * from './build'\nexport * from './plugins'\n\n// Re-export MCP-specific types and functions\nexport type { McpToolName, EventMcpToolUsage } from './build'\nexport { EVENT_MCP_TOOL_USAGE, eventMcpToolUsage } from './build'\n"],"names":["EVENT_MCP_TOOL_USAGE","eventMcpToolUsage"],"mappings":";;;;;;;;;;;;;;;IAMSA,oBAAoB;eAApBA,2BAAoB;;IAAEC,iBAAiB;eAAjBA,wBAAiB;;;;qBANlC;oCACA;qBACA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/mcp-telemetry.test.js b/e-commerce/node_modules/next/dist/telemetry/events/mcp-telemetry.test.js new file mode 100644 index 0000000000000000000000000000000000000000..465f996a529ac06902c1d2b897a011053055eca8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/mcp-telemetry.test.js @@ -0,0 +1,111 @@ +/** + * @jest-environment node + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _build = require("./build"); +describe('MCP Telemetry Events', ()=>{ + it('should generate correct telemetry events for single tool', ()=>{ + const usages = [ + { + featureName: 'mcp/get_errors', + invocationCount: 5 + } + ]; + const events = (0, _build.eventMcpToolUsage)(usages); + expect(events).toHaveLength(1); + expect(events[0]).toEqual({ + eventName: _build.EVENT_MCP_TOOL_USAGE, + payload: { + toolName: 'mcp/get_errors', + invocationCount: 5 + } + }); + }); + it('should generate correct telemetry events for multiple tools', ()=>{ + const usages = [ + { + featureName: 'mcp/get_errors', + invocationCount: 3 + }, + { + featureName: 'mcp/get_logs', + invocationCount: 1 + }, + { + featureName: 'mcp/get_page_metadata', + invocationCount: 7 + } + ]; + const events = (0, _build.eventMcpToolUsage)(usages); + expect(events).toHaveLength(3); + expect(events[0]).toEqual({ + eventName: _build.EVENT_MCP_TOOL_USAGE, + payload: { + toolName: 'mcp/get_errors', + invocationCount: 3 + } + }); + expect(events[1]).toEqual({ + eventName: _build.EVENT_MCP_TOOL_USAGE, + payload: { + toolName: 'mcp/get_logs', + invocationCount: 1 + } + }); + expect(events[2]).toEqual({ + eventName: _build.EVENT_MCP_TOOL_USAGE, + payload: { + toolName: 'mcp/get_page_metadata', + invocationCount: 7 + } + }); + }); + it('should handle all MCP tool types', ()=>{ + const allTools = [ + 'mcp/get_errors', + 'mcp/get_logs', + 'mcp/get_page_metadata', + 'mcp/get_project_metadata', + 'mcp/get_routes', + 'mcp/get_request_insights', + 'mcp/get_server_action_by_id', + 'mcp/get_compilation_issues', + 'mcp/compile_route' + ]; + const usages = allTools.map((tool, index)=>({ + featureName: tool, + invocationCount: index + 1 + })); + const events = (0, _build.eventMcpToolUsage)(usages); + expect(events).toHaveLength(9); + events.forEach((event, index)=>{ + expect(event.eventName).toBe(_build.EVENT_MCP_TOOL_USAGE); + expect(event.payload.toolName).toBe(allTools[index]); + expect(event.payload.invocationCount).toBe(index + 1); + }); + }); + it('should handle empty usage array', ()=>{ + const events = (0, _build.eventMcpToolUsage)([]); + expect(events).toEqual([]); + }); + it('should use correct event name constant', ()=>{ + expect(_build.EVENT_MCP_TOOL_USAGE).toBe('NEXT_MCP_TOOL_USAGE'); + }); + it('should transform featureName to toolName in payload', ()=>{ + const usages = [ + { + featureName: 'mcp/get_project_metadata', + invocationCount: 2 + } + ]; + const events = (0, _build.eventMcpToolUsage)(usages); + // Verify the input has 'featureName' but output has 'toolName' + expect(usages[0]).toHaveProperty('featureName'); + expect(events[0].payload).toHaveProperty('toolName'); + expect(events[0].payload).not.toHaveProperty('featureName'); + }); +}); + +//# sourceMappingURL=mcp-telemetry.test.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/mcp-telemetry.test.js.map b/e-commerce/node_modules/next/dist/telemetry/events/mcp-telemetry.test.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f3005b0eca19f7e708f17df80ae28131522b35fb --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/mcp-telemetry.test.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/mcp-telemetry.test.ts"],"sourcesContent":["/**\n * @jest-environment node\n */\n\nimport { eventMcpToolUsage, EVENT_MCP_TOOL_USAGE } from './build'\nimport type { McpToolName } from './build'\n\ndescribe('MCP Telemetry Events', () => {\n it('should generate correct telemetry events for single tool', () => {\n const usages = [\n {\n featureName: 'mcp/get_errors' as McpToolName,\n invocationCount: 5,\n },\n ]\n\n const events = eventMcpToolUsage(usages)\n\n expect(events).toHaveLength(1)\n expect(events[0]).toEqual({\n eventName: EVENT_MCP_TOOL_USAGE,\n payload: {\n toolName: 'mcp/get_errors',\n invocationCount: 5,\n },\n })\n })\n\n it('should generate correct telemetry events for multiple tools', () => {\n const usages = [\n {\n featureName: 'mcp/get_errors' as McpToolName,\n invocationCount: 3,\n },\n {\n featureName: 'mcp/get_logs' as McpToolName,\n invocationCount: 1,\n },\n {\n featureName: 'mcp/get_page_metadata' as McpToolName,\n invocationCount: 7,\n },\n ]\n\n const events = eventMcpToolUsage(usages)\n\n expect(events).toHaveLength(3)\n\n expect(events[0]).toEqual({\n eventName: EVENT_MCP_TOOL_USAGE,\n payload: {\n toolName: 'mcp/get_errors',\n invocationCount: 3,\n },\n })\n\n expect(events[1]).toEqual({\n eventName: EVENT_MCP_TOOL_USAGE,\n payload: {\n toolName: 'mcp/get_logs',\n invocationCount: 1,\n },\n })\n\n expect(events[2]).toEqual({\n eventName: EVENT_MCP_TOOL_USAGE,\n payload: {\n toolName: 'mcp/get_page_metadata',\n invocationCount: 7,\n },\n })\n })\n\n it('should handle all MCP tool types', () => {\n const allTools: McpToolName[] = [\n 'mcp/get_errors',\n 'mcp/get_logs',\n 'mcp/get_page_metadata',\n 'mcp/get_project_metadata',\n 'mcp/get_routes',\n 'mcp/get_request_insights',\n 'mcp/get_server_action_by_id',\n 'mcp/get_compilation_issues',\n 'mcp/compile_route',\n ]\n\n const usages = allTools.map((tool, index) => ({\n featureName: tool,\n invocationCount: index + 1,\n }))\n\n const events = eventMcpToolUsage(usages)\n\n expect(events).toHaveLength(9)\n\n events.forEach((event, index) => {\n expect(event.eventName).toBe(EVENT_MCP_TOOL_USAGE)\n expect(event.payload.toolName).toBe(allTools[index])\n expect(event.payload.invocationCount).toBe(index + 1)\n })\n })\n\n it('should handle empty usage array', () => {\n const events = eventMcpToolUsage([])\n expect(events).toEqual([])\n })\n\n it('should use correct event name constant', () => {\n expect(EVENT_MCP_TOOL_USAGE).toBe('NEXT_MCP_TOOL_USAGE')\n })\n\n it('should transform featureName to toolName in payload', () => {\n const usages = [\n {\n featureName: 'mcp/get_project_metadata' as McpToolName,\n invocationCount: 2,\n },\n ]\n\n const events = eventMcpToolUsage(usages)\n\n // Verify the input has 'featureName' but output has 'toolName'\n expect(usages[0]).toHaveProperty('featureName')\n expect(events[0].payload).toHaveProperty('toolName')\n expect(events[0].payload).not.toHaveProperty('featureName')\n })\n})\n"],"names":["describe","it","usages","featureName","invocationCount","events","eventMcpToolUsage","expect","toHaveLength","toEqual","eventName","EVENT_MCP_TOOL_USAGE","payload","toolName","allTools","map","tool","index","forEach","event","toBe","toHaveProperty","not"],"mappings":"AAAA;;CAEC;;;;uBAEuD;AAGxDA,SAAS,wBAAwB;IAC/BC,GAAG,4DAA4D;QAC7D,MAAMC,SAAS;YACb;gBACEC,aAAa;gBACbC,iBAAiB;YACnB;SACD;QAED,MAAMC,SAASC,IAAAA,wBAAiB,EAACJ;QAEjCK,OAAOF,QAAQG,YAAY,CAAC;QAC5BD,OAAOF,MAAM,CAAC,EAAE,EAAEI,OAAO,CAAC;YACxBC,WAAWC,2BAAoB;YAC/BC,SAAS;gBACPC,UAAU;gBACVT,iBAAiB;YACnB;QACF;IACF;IAEAH,GAAG,+DAA+D;QAChE,MAAMC,SAAS;YACb;gBACEC,aAAa;gBACbC,iBAAiB;YACnB;YACA;gBACED,aAAa;gBACbC,iBAAiB;YACnB;YACA;gBACED,aAAa;gBACbC,iBAAiB;YACnB;SACD;QAED,MAAMC,SAASC,IAAAA,wBAAiB,EAACJ;QAEjCK,OAAOF,QAAQG,YAAY,CAAC;QAE5BD,OAAOF,MAAM,CAAC,EAAE,EAAEI,OAAO,CAAC;YACxBC,WAAWC,2BAAoB;YAC/BC,SAAS;gBACPC,UAAU;gBACVT,iBAAiB;YACnB;QACF;QAEAG,OAAOF,MAAM,CAAC,EAAE,EAAEI,OAAO,CAAC;YACxBC,WAAWC,2BAAoB;YAC/BC,SAAS;gBACPC,UAAU;gBACVT,iBAAiB;YACnB;QACF;QAEAG,OAAOF,MAAM,CAAC,EAAE,EAAEI,OAAO,CAAC;YACxBC,WAAWC,2BAAoB;YAC/BC,SAAS;gBACPC,UAAU;gBACVT,iBAAiB;YACnB;QACF;IACF;IAEAH,GAAG,oCAAoC;QACrC,MAAMa,WAA0B;YAC9B;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QAED,MAAMZ,SAASY,SAASC,GAAG,CAAC,CAACC,MAAMC,QAAW,CAAA;gBAC5Cd,aAAaa;gBACbZ,iBAAiBa,QAAQ;YAC3B,CAAA;QAEA,MAAMZ,SAASC,IAAAA,wBAAiB,EAACJ;QAEjCK,OAAOF,QAAQG,YAAY,CAAC;QAE5BH,OAAOa,OAAO,CAAC,CAACC,OAAOF;YACrBV,OAAOY,MAAMT,SAAS,EAAEU,IAAI,CAACT,2BAAoB;YACjDJ,OAAOY,MAAMP,OAAO,CAACC,QAAQ,EAAEO,IAAI,CAACN,QAAQ,CAACG,MAAM;YACnDV,OAAOY,MAAMP,OAAO,CAACR,eAAe,EAAEgB,IAAI,CAACH,QAAQ;QACrD;IACF;IAEAhB,GAAG,mCAAmC;QACpC,MAAMI,SAASC,IAAAA,wBAAiB,EAAC,EAAE;QACnCC,OAAOF,QAAQI,OAAO,CAAC,EAAE;IAC3B;IAEAR,GAAG,0CAA0C;QAC3CM,OAAOI,2BAAoB,EAAES,IAAI,CAAC;IACpC;IAEAnB,GAAG,uDAAuD;QACxD,MAAMC,SAAS;YACb;gBACEC,aAAa;gBACbC,iBAAiB;YACnB;SACD;QAED,MAAMC,SAASC,IAAAA,wBAAiB,EAACJ;QAEjC,+DAA+D;QAC/DK,OAAOL,MAAM,CAAC,EAAE,EAAEmB,cAAc,CAAC;QACjCd,OAAOF,MAAM,CAAC,EAAE,CAACO,OAAO,EAAES,cAAc,CAAC;QACzCd,OAAOF,MAAM,CAAC,EAAE,CAACO,OAAO,EAAEU,GAAG,CAACD,cAAc,CAAC;IAC/C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/plugins.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/plugins.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..80fba55e232c783537236a07eead6d4a09ea431a --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/plugins.d.ts @@ -0,0 +1,9 @@ +type NextPluginsEvent = { + eventName: string; + payload: { + packageName: string; + packageVersion: string; + }; +}; +export declare function eventNextPlugins(dir: string): Promise>; +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/plugins.js b/e-commerce/node_modules/next/dist/telemetry/events/plugins.js new file mode 100644 index 0000000000000000000000000000000000000000..63e10418b79e10f9e338b9a1b5f23d164f9453dd --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/plugins.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "eventNextPlugins", { + enumerable: true, + get: function() { + return eventNextPlugins; + } +}); +const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const EVENT_PLUGIN_PRESENT = 'NEXT_PACKAGE_DETECTED'; +async function eventNextPlugins(dir) { + try { + const packageJsonPath = await (0, _findup.default)('package.json', { + cwd: dir + }); + if (!packageJsonPath) { + return []; + } + const { dependencies = {}, devDependencies = {} } = require(packageJsonPath); + const deps = { + ...devDependencies, + ...dependencies + }; + return Object.keys(deps).reduce((events, plugin)=>{ + const version = deps[plugin]; + // Don't add deps without a version set + if (!version) { + return events; + } + events.push({ + eventName: EVENT_PLUGIN_PRESENT, + payload: { + packageName: plugin, + packageVersion: version + } + }); + return events; + }, []); + } catch (_) { + return []; + } +} + +//# sourceMappingURL=plugins.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/plugins.js.map b/e-commerce/node_modules/next/dist/telemetry/events/plugins.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d0f3dce74fd09a7c7171148de9277fdafea87c4f --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/plugins.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/plugins.ts"],"sourcesContent":["import findUp from 'next/dist/compiled/find-up'\n\nconst EVENT_PLUGIN_PRESENT = 'NEXT_PACKAGE_DETECTED'\ntype NextPluginsEvent = {\n eventName: string\n payload: {\n packageName: string\n packageVersion: string\n }\n}\n\nexport async function eventNextPlugins(\n dir: string\n): Promise> {\n try {\n const packageJsonPath = await findUp('package.json', { cwd: dir })\n if (!packageJsonPath) {\n return []\n }\n\n const { dependencies = {}, devDependencies = {} } = require(packageJsonPath)\n\n const deps = { ...devDependencies, ...dependencies }\n\n return Object.keys(deps).reduce(\n (events: NextPluginsEvent[], plugin: string): NextPluginsEvent[] => {\n const version = deps[plugin]\n // Don't add deps without a version set\n if (!version) {\n return events\n }\n\n events.push({\n eventName: EVENT_PLUGIN_PRESENT,\n payload: {\n packageName: plugin,\n packageVersion: version,\n },\n })\n\n return events\n },\n []\n )\n } catch (_) {\n return []\n }\n}\n"],"names":["eventNextPlugins","EVENT_PLUGIN_PRESENT","dir","packageJsonPath","findUp","cwd","dependencies","devDependencies","require","deps","Object","keys","reduce","events","plugin","version","push","eventName","payload","packageName","packageVersion","_"],"mappings":";;;;+BAWsBA;;;eAAAA;;;+DAXH;;;;;;AAEnB,MAAMC,uBAAuB;AAStB,eAAeD,iBACpBE,GAAW;IAEX,IAAI;QACF,MAAMC,kBAAkB,MAAMC,IAAAA,eAAM,EAAC,gBAAgB;YAAEC,KAAKH;QAAI;QAChE,IAAI,CAACC,iBAAiB;YACpB,OAAO,EAAE;QACX;QAEA,MAAM,EAAEG,eAAe,CAAC,CAAC,EAAEC,kBAAkB,CAAC,CAAC,EAAE,GAAGC,QAAQL;QAE5D,MAAMM,OAAO;YAAE,GAAGF,eAAe;YAAE,GAAGD,YAAY;QAAC;QAEnD,OAAOI,OAAOC,IAAI,CAACF,MAAMG,MAAM,CAC7B,CAACC,QAA4BC;YAC3B,MAAMC,UAAUN,IAAI,CAACK,OAAO;YAC5B,uCAAuC;YACvC,IAAI,CAACC,SAAS;gBACZ,OAAOF;YACT;YAEAA,OAAOG,IAAI,CAAC;gBACVC,WAAWhB;gBACXiB,SAAS;oBACPC,aAAaL;oBACbM,gBAAgBL;gBAClB;YACF;YAEA,OAAOF;QACT,GACA,EAAE;IAEN,EAAE,OAAOQ,GAAG;QACV,OAAO,EAAE;IACX;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5232da12e54b0a0f3e405e9f1906197968196dc3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.d.ts @@ -0,0 +1,14 @@ +export type EventCliSessionStopped = { + cliCommand: string; + nextVersion: string; + nodeVersion: string; + turboFlag?: boolean | null; + durationMilliseconds?: number | null; + pagesDir?: boolean; + appDir?: boolean; + isRspack: boolean; +}; +export declare function eventCliSessionStopped(event: Omit): { + eventName: string; + payload: EventCliSessionStopped; +}[]; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.js b/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.js new file mode 100644 index 0000000000000000000000000000000000000000..aa92a1ec01816249b29bc29dc0f1c1782331c6bb --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "eventCliSessionStopped", { + enumerable: true, + get: function() { + return eventCliSessionStopped; + } +}); +const EVENT_VERSION = 'NEXT_CLI_SESSION_STOPPED'; +function eventCliSessionStopped(event) { + // This should be an invariant, if it fails our build tooling is broken. + if (typeof "16.4.0" !== 'string') { + return []; + } + const payload = { + nextVersion: "16.4.0", + nodeVersion: process.version, + cliCommand: event.cliCommand, + durationMilliseconds: event.durationMilliseconds, + ...typeof event.turboFlag !== 'undefined' ? { + turboFlag: !!event.turboFlag + } : {}, + pagesDir: event.pagesDir, + appDir: event.appDir, + isRspack: process.env.NEXT_RSPACK !== undefined + }; + return [ + { + eventName: EVENT_VERSION, + payload + } + ]; +} + +//# sourceMappingURL=session-stopped.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.js.map b/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6fe4707575f650d0bd1b650a06d79ee6c7453d78 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/session-stopped.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/session-stopped.ts"],"sourcesContent":["const EVENT_VERSION = 'NEXT_CLI_SESSION_STOPPED'\n\nexport type EventCliSessionStopped = {\n cliCommand: string\n nextVersion: string\n nodeVersion: string\n turboFlag?: boolean | null\n durationMilliseconds?: number | null\n pagesDir?: boolean\n appDir?: boolean\n isRspack: boolean\n}\n\nexport function eventCliSessionStopped(\n event: Omit<\n EventCliSessionStopped,\n 'nextVersion' | 'nodeVersion' | 'isRspack'\n >\n): { eventName: string; payload: EventCliSessionStopped }[] {\n // This should be an invariant, if it fails our build tooling is broken.\n if (typeof process.env.__NEXT_VERSION !== 'string') {\n return []\n }\n\n const payload: EventCliSessionStopped = {\n nextVersion: process.env.__NEXT_VERSION,\n nodeVersion: process.version,\n cliCommand: event.cliCommand,\n durationMilliseconds: event.durationMilliseconds,\n ...(typeof event.turboFlag !== 'undefined'\n ? {\n turboFlag: !!event.turboFlag,\n }\n : {}),\n pagesDir: event.pagesDir,\n appDir: event.appDir,\n isRspack: process.env.NEXT_RSPACK !== undefined,\n }\n return [{ eventName: EVENT_VERSION, payload }]\n}\n"],"names":["eventCliSessionStopped","EVENT_VERSION","event","process","env","__NEXT_VERSION","payload","nextVersion","nodeVersion","version","cliCommand","durationMilliseconds","turboFlag","pagesDir","appDir","isRspack","NEXT_RSPACK","undefined","eventName"],"mappings":";;;;+BAagBA;;;eAAAA;;;AAbhB,MAAMC,gBAAgB;AAaf,SAASD,uBACdE,KAGC;IAED,wEAAwE;IACxE,IAAI,OAAOC,QAAQC,GAAG,CAACC,cAAc,KAAK,UAAU;QAClD,OAAO,EAAE;IACX;IAEA,MAAMC,UAAkC;QACtCC,aAAaJ,QAAQC,GAAG,CAACC,cAAc;QACvCG,aAAaL,QAAQM,OAAO;QAC5BC,YAAYR,MAAMQ,UAAU;QAC5BC,sBAAsBT,MAAMS,oBAAoB;QAChD,GAAI,OAAOT,MAAMU,SAAS,KAAK,cAC3B;YACEA,WAAW,CAAC,CAACV,MAAMU,SAAS;QAC9B,IACA,CAAC,CAAC;QACNC,UAAUX,MAAMW,QAAQ;QACxBC,QAAQZ,MAAMY,MAAM;QACpBC,UAAUZ,QAAQC,GAAG,CAACY,WAAW,KAAKC;IACxC;IACA,OAAO;QAAC;YAAEC,WAAWjB;YAAeK;QAAQ;KAAE;AAChD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..faf24c65b30970420fda523e15f8fda396df54a9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.d.ts @@ -0,0 +1,14 @@ +export type EventSwcLoadFailure = { + eventName: string; + payload: { + platform: string; + arch: string; + nodeVersion: string; + nextVersion: string; + wasm?: 'enabled' | 'fallback' | 'failed'; + glibcVersion?: string; + installedSwcPackages?: string; + nativeBindingsErrorCode?: string; + }; +}; +export declare function eventSwcLoadFailure(event?: Pick): Promise; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.js b/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.js new file mode 100644 index 0000000000000000000000000000000000000000..fc12b16e020efc8f1bff19fbd30d8a1e1b491634 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "eventSwcLoadFailure", { + enumerable: true, + get: function() { + return eventSwcLoadFailure; + } +}); +const _shared = require("../../trace/shared"); +const _packagejson = require("next/package.json"); +const EVENT_PLUGIN_PRESENT = 'NEXT_SWC_LOAD_FAILURE'; +async function eventSwcLoadFailure(event) { + const telemetry = _shared.traceGlobals.get('telemetry'); + // can't continue if telemetry isn't set + if (!telemetry) return; + let glibcVersion; + let installedSwcPackages; + try { + var _process_report; + // @ts-ignore + glibcVersion = (_process_report = process.report) == null ? void 0 : _process_report.getReport().header.glibcVersionRuntime; + } catch {} + try { + const pkgNames = Object.keys(_packagejson.optionalDependencies || {}).filter((pkg)=>pkg.startsWith('@next/swc')); + const installedPkgs = []; + for (const pkg of pkgNames){ + try { + const { version } = require(`${pkg}/package.json`); + installedPkgs.push(`${pkg}@${version}`); + } catch {} + } + if (installedPkgs.length > 0) { + installedSwcPackages = installedPkgs.sort().join(','); + } + } catch {} + telemetry.record({ + eventName: EVENT_PLUGIN_PRESENT, + payload: { + nextVersion: "16.4.0", + glibcVersion, + installedSwcPackages, + arch: process.arch, + platform: process.platform, + nodeVersion: process.versions.node, + wasm: event == null ? void 0 : event.wasm, + nativeBindingsErrorCode: event == null ? void 0 : event.nativeBindingsErrorCode + } + }); + // ensure this event is flushed before process exits + await telemetry.flush(); +} + +//# sourceMappingURL=swc-load-failure.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.js.map b/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.js.map new file mode 100644 index 0000000000000000000000000000000000000000..79e713c91c64f47ad15951ed6ddf9ed690d8aa92 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/swc-load-failure.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/swc-load-failure.ts"],"sourcesContent":["import { traceGlobals } from '../../trace/shared'\nimport type { Telemetry } from '../storage'\n// @ts-ignore JSON\nimport { optionalDependencies } from 'next/package.json'\n\nconst EVENT_PLUGIN_PRESENT = 'NEXT_SWC_LOAD_FAILURE'\nexport type EventSwcLoadFailure = {\n eventName: string\n payload: {\n platform: string\n arch: string\n nodeVersion: string\n nextVersion: string\n wasm?: 'enabled' | 'fallback' | 'failed'\n glibcVersion?: string\n installedSwcPackages?: string\n nativeBindingsErrorCode?: string\n }\n}\n\nexport async function eventSwcLoadFailure(\n event?: Pick<\n EventSwcLoadFailure['payload'],\n 'wasm' | 'nativeBindingsErrorCode'\n >\n): Promise {\n const telemetry: Telemetry | undefined = traceGlobals.get('telemetry')\n // can't continue if telemetry isn't set\n if (!telemetry) return\n\n let glibcVersion\n let installedSwcPackages\n\n try {\n // @ts-ignore\n glibcVersion = process.report?.getReport().header.glibcVersionRuntime\n } catch {}\n\n try {\n const pkgNames = Object.keys(optionalDependencies || {}).filter((pkg) =>\n pkg.startsWith('@next/swc')\n )\n const installedPkgs = []\n\n for (const pkg of pkgNames) {\n try {\n const { version } = require(`${pkg}/package.json`)\n installedPkgs.push(`${pkg}@${version}`)\n } catch {}\n }\n\n if (installedPkgs.length > 0) {\n installedSwcPackages = installedPkgs.sort().join(',')\n }\n } catch {}\n\n telemetry.record({\n eventName: EVENT_PLUGIN_PRESENT,\n payload: {\n nextVersion: process.env.__NEXT_VERSION as string,\n glibcVersion,\n installedSwcPackages,\n arch: process.arch,\n platform: process.platform,\n nodeVersion: process.versions.node,\n wasm: event?.wasm,\n nativeBindingsErrorCode: event?.nativeBindingsErrorCode,\n },\n })\n // ensure this event is flushed before process exits\n await telemetry.flush()\n}\n"],"names":["eventSwcLoadFailure","EVENT_PLUGIN_PRESENT","event","telemetry","traceGlobals","get","glibcVersion","installedSwcPackages","process","report","getReport","header","glibcVersionRuntime","pkgNames","Object","keys","optionalDependencies","filter","pkg","startsWith","installedPkgs","version","require","push","length","sort","join","record","eventName","payload","nextVersion","env","__NEXT_VERSION","arch","platform","nodeVersion","versions","node","wasm","nativeBindingsErrorCode","flush"],"mappings":";;;;+BAoBsBA;;;eAAAA;;;wBApBO;6BAGQ;AAErC,MAAMC,uBAAuB;AAetB,eAAeD,oBACpBE,KAGC;IAED,MAAMC,YAAmCC,oBAAY,CAACC,GAAG,CAAC;IAC1D,wCAAwC;IACxC,IAAI,CAACF,WAAW;IAEhB,IAAIG;IACJ,IAAIC;IAEJ,IAAI;YAEaC;QADf,aAAa;QACbF,gBAAeE,kBAAAA,QAAQC,MAAM,qBAAdD,gBAAgBE,SAAS,GAAGC,MAAM,CAACC,mBAAmB;IACvE,EAAE,OAAM,CAAC;IAET,IAAI;QACF,MAAMC,WAAWC,OAAOC,IAAI,CAACC,iCAAoB,IAAI,CAAC,GAAGC,MAAM,CAAC,CAACC,MAC/DA,IAAIC,UAAU,CAAC;QAEjB,MAAMC,gBAAgB,EAAE;QAExB,KAAK,MAAMF,OAAOL,SAAU;YAC1B,IAAI;gBACF,MAAM,EAAEQ,OAAO,EAAE,GAAGC,QAAQ,GAAGJ,IAAI,aAAa,CAAC;gBACjDE,cAAcG,IAAI,CAAC,GAAGL,IAAI,CAAC,EAAEG,SAAS;YACxC,EAAE,OAAM,CAAC;QACX;QAEA,IAAID,cAAcI,MAAM,GAAG,GAAG;YAC5BjB,uBAAuBa,cAAcK,IAAI,GAAGC,IAAI,CAAC;QACnD;IACF,EAAE,OAAM,CAAC;IAETvB,UAAUwB,MAAM,CAAC;QACfC,WAAW3B;QACX4B,SAAS;YACPC,aAAatB,QAAQuB,GAAG,CAACC,cAAc;YACvC1B;YACAC;YACA0B,MAAMzB,QAAQyB,IAAI;YAClBC,UAAU1B,QAAQ0B,QAAQ;YAC1BC,aAAa3B,QAAQ4B,QAAQ,CAACC,IAAI;YAClCC,IAAI,EAAEpC,yBAAAA,MAAOoC,IAAI;YACjBC,uBAAuB,EAAErC,yBAAAA,MAAOqC,uBAAuB;QACzD;IACF;IACA,oDAAoD;IACpD,MAAMpC,UAAUqC,KAAK;AACvB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d53e2dcffd4e6ca95dec3051ee1cfcbeca7ddd3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.d.ts @@ -0,0 +1,10 @@ +import type { NextConfig } from '../../server/config-shared'; +type SwcPluginsEvent = { + eventName: string; + payload: { + pluginName: string; + pluginVersion?: string; + }; +}; +export declare function eventSwcPlugins(dir: string, config: NextConfig): Promise>; +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.js b/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.js new file mode 100644 index 0000000000000000000000000000000000000000..0be253679087eb8cbb8a5508f6c3af1621ca5afe --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "eventSwcPlugins", { + enumerable: true, + get: function() { + return eventSwcPlugins; + } +}); +const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const EVENT_SWC_PLUGIN_PRESENT = 'NEXT_SWC_PLUGIN_DETECTED'; +async function eventSwcPlugins(dir, config) { + try { + var _config_experimental_swcPlugins, _config_experimental; + const packageJsonPath = await (0, _findup.default)('package.json', { + cwd: dir + }); + if (!packageJsonPath) { + return []; + } + const { dependencies = {}, devDependencies = {} } = require(packageJsonPath); + const deps = { + ...devDependencies, + ...dependencies + }; + const swcPluginPackages = ((_config_experimental = config.experimental) == null ? void 0 : (_config_experimental_swcPlugins = _config_experimental.swcPlugins) == null ? void 0 : _config_experimental_swcPlugins.map(([name, _])=>name)) ?? []; + return swcPluginPackages.map((plugin)=>{ + // swc plugins can be non-npm pkgs with absolute path doesn't have version + const version = deps[plugin] ?? undefined; + let pluginName = plugin; + if (_fs.default.existsSync(pluginName)) { + pluginName = _path.default.basename(plugin, '.wasm'); + } + return { + eventName: EVENT_SWC_PLUGIN_PRESENT, + payload: { + pluginName: pluginName, + pluginVersion: version + } + }; + }); + } catch (_) { + return []; + } +} + +//# sourceMappingURL=swc-plugins.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.js.map b/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.js.map new file mode 100644 index 0000000000000000000000000000000000000000..59a8d614ece2340a6edbe3d6fe9e8da4d7a267f5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/swc-plugins.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/swc-plugins.ts"],"sourcesContent":["import findUp from 'next/dist/compiled/find-up'\nimport path from 'path'\nimport fs from 'fs'\nimport type { NextConfig } from '../../server/config-shared'\n\nconst EVENT_SWC_PLUGIN_PRESENT = 'NEXT_SWC_PLUGIN_DETECTED'\ntype SwcPluginsEvent = {\n eventName: string\n payload: {\n pluginName: string\n pluginVersion?: string\n }\n}\n\nexport async function eventSwcPlugins(\n dir: string,\n config: NextConfig\n): Promise> {\n try {\n const packageJsonPath = await findUp('package.json', { cwd: dir })\n if (!packageJsonPath) {\n return []\n }\n\n const { dependencies = {}, devDependencies = {} } = require(packageJsonPath)\n\n const deps = { ...devDependencies, ...dependencies }\n const swcPluginPackages =\n config.experimental?.swcPlugins?.map(([name, _]) => name) ?? []\n\n return swcPluginPackages.map((plugin) => {\n // swc plugins can be non-npm pkgs with absolute path doesn't have version\n const version = deps[plugin] ?? undefined\n let pluginName = plugin\n if (fs.existsSync(pluginName)) {\n pluginName = path.basename(plugin, '.wasm')\n }\n\n return {\n eventName: EVENT_SWC_PLUGIN_PRESENT,\n payload: {\n pluginName: pluginName,\n pluginVersion: version,\n },\n }\n })\n } catch (_) {\n return []\n }\n}\n"],"names":["eventSwcPlugins","EVENT_SWC_PLUGIN_PRESENT","dir","config","packageJsonPath","findUp","cwd","dependencies","devDependencies","require","deps","swcPluginPackages","experimental","swcPlugins","map","name","_","plugin","version","undefined","pluginName","fs","existsSync","path","basename","eventName","payload","pluginVersion"],"mappings":";;;;+BAcsBA;;;eAAAA;;;+DAdH;6DACF;2DACF;;;;;;AAGf,MAAMC,2BAA2B;AAS1B,eAAeD,gBACpBE,GAAW,EACXC,MAAkB;IAElB,IAAI;YAUAA,iCAAAA;QATF,MAAMC,kBAAkB,MAAMC,IAAAA,eAAM,EAAC,gBAAgB;YAAEC,KAAKJ;QAAI;QAChE,IAAI,CAACE,iBAAiB;YACpB,OAAO,EAAE;QACX;QAEA,MAAM,EAAEG,eAAe,CAAC,CAAC,EAAEC,kBAAkB,CAAC,CAAC,EAAE,GAAGC,QAAQL;QAE5D,MAAMM,OAAO;YAAE,GAAGF,eAAe;YAAE,GAAGD,YAAY;QAAC;QACnD,MAAMI,oBACJR,EAAAA,uBAAAA,OAAOS,YAAY,sBAAnBT,kCAAAA,qBAAqBU,UAAU,qBAA/BV,gCAAiCW,GAAG,CAAC,CAAC,CAACC,MAAMC,EAAE,GAAKD,UAAS,EAAE;QAEjE,OAAOJ,kBAAkBG,GAAG,CAAC,CAACG;YAC5B,0EAA0E;YAC1E,MAAMC,UAAUR,IAAI,CAACO,OAAO,IAAIE;YAChC,IAAIC,aAAaH;YACjB,IAAII,WAAE,CAACC,UAAU,CAACF,aAAa;gBAC7BA,aAAaG,aAAI,CAACC,QAAQ,CAACP,QAAQ;YACrC;YAEA,OAAO;gBACLQ,WAAWxB;gBACXyB,SAAS;oBACPN,YAAYA;oBACZO,eAAeT;gBACjB;YACF;QACF;IACF,EAAE,OAAOF,GAAG;QACV,OAAO,EAAE;IACX;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/version.d.ts b/e-commerce/node_modules/next/dist/telemetry/events/version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ed0b7e4c4440306d23ee8db78bf90b7538fb4a6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/version.d.ts @@ -0,0 +1,47 @@ +import type { NextConfigComplete } from '../../server/config-shared'; +type EventCliSessionStarted = { + nextVersion: string; + nodeVersion: string; + cliCommand: string; + isSrcDir: boolean | null; + hasNowJson: boolean; + isCustomServer: boolean | null; + hasNextConfig: boolean; + buildTarget: string; + hasWebpackConfig: boolean; + hasBabelConfig: boolean; + basePathEnabled: boolean; + i18nEnabled: boolean; + imageEnabled: boolean; + imageFutureEnabled: boolean; + locales: string | null; + localeDomainsCount: number | null; + localeDetectionEnabled: boolean | null; + imageDomainsCount: number | null; + imageRemotePatternsCount: number | null; + imageLocalPatternsCount: number | null; + imageQualities: string | null; + imageSizes: string | null; + imageLoader: string | null; + imageFormats: string | null; + nextConfigOutput: string | null; + trailingSlashEnabled: boolean; + reactStrictMode: boolean; + webpackVersion: number | null; + turboFlag: boolean; + useTurbopackWorkerAssetPrefix: boolean; + isRspack: boolean; + appDir: boolean | null; + pagesDir: boolean | null; + staticStaleTime: number | null; + dynamicStaleTime: number | null; + reactCompiler: boolean; + reactCompilerCompilationMode: string | null; + reactCompilerPanicThreshold: string | null; + adapterPath: boolean; +}; +export declare function eventCliSession(nextConfig: NextConfigComplete, event: Omit): { + eventName: string; + payload: EventCliSessionStarted; +}[]; +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/events/version.js b/e-commerce/node_modules/next/dist/telemetry/events/version.js new file mode 100644 index 0000000000000000000000000000000000000000..b8bc60e8961d282301fd04e2738ec1b0761c09c7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/version.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "eventCliSession", { + enumerable: true, + get: function() { + return eventCliSession; + } +}); +const EVENT_VERSION = 'NEXT_CLI_SESSION_STARTED'; +function eventCliSession(nextConfig, event) { + var _nextConfig_experimental, _nextConfig_experimental_staleTimes, _nextConfig_experimental_staleTimes1, _nextConfig_reactCompiler, _nextConfig_reactCompiler1; + // This should be an invariant, if it fails our build tooling is broken. + if (typeof "16.4.0" !== 'string') { + return []; + } + const { images, i18n } = nextConfig || {}; + const payload = { + nextVersion: "16.4.0", + nodeVersion: process.version, + cliCommand: event.cliCommand, + isSrcDir: event.isSrcDir, + hasNowJson: event.hasNowJson, + isCustomServer: event.isCustomServer, + hasNextConfig: nextConfig.configOrigin !== 'default', + buildTarget: 'default', + hasWebpackConfig: typeof (nextConfig == null ? void 0 : nextConfig.webpack) === 'function', + hasBabelConfig: false, + imageEnabled: !!images, + imageFutureEnabled: !!images, + basePathEnabled: !!(nextConfig == null ? void 0 : nextConfig.basePath), + i18nEnabled: !!i18n, + locales: (i18n == null ? void 0 : i18n.locales) ? i18n.locales.join(',') : null, + localeDomainsCount: (i18n == null ? void 0 : i18n.domains) ? i18n.domains.length : null, + localeDetectionEnabled: !i18n ? null : i18n.localeDetection !== false, + imageDomainsCount: (images == null ? void 0 : images.domains) ? images.domains.length : null, + imageRemotePatternsCount: (images == null ? void 0 : images.remotePatterns) ? images.remotePatterns.length : null, + imageLocalPatternsCount: (images == null ? void 0 : images.localPatterns) ? images.localPatterns.length : null, + imageSizes: (images == null ? void 0 : images.imageSizes) ? images.imageSizes.join(',') : null, + imageQualities: (images == null ? void 0 : images.qualities) ? images.qualities.join(',') : null, + imageLoader: images == null ? void 0 : images.loader, + imageFormats: (images == null ? void 0 : images.formats) ? images.formats.join(',') : null, + nextConfigOutput: (nextConfig == null ? void 0 : nextConfig.output) || null, + trailingSlashEnabled: !!(nextConfig == null ? void 0 : nextConfig.trailingSlash), + reactStrictMode: !!(nextConfig == null ? void 0 : nextConfig.reactStrictMode), + webpackVersion: event.webpackVersion || null, + turboFlag: event.turboFlag || false, + useTurbopackWorkerAssetPrefix: (nextConfig == null ? void 0 : (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.turbopackWorkerAssetPrefix) !== undefined, + isRspack: process.env.NEXT_RSPACK !== undefined, + appDir: event.appDir, + pagesDir: event.pagesDir, + staticStaleTime: ((_nextConfig_experimental_staleTimes = nextConfig.experimental.staleTimes) == null ? void 0 : _nextConfig_experimental_staleTimes.static) ?? null, + dynamicStaleTime: ((_nextConfig_experimental_staleTimes1 = nextConfig.experimental.staleTimes) == null ? void 0 : _nextConfig_experimental_staleTimes1.dynamic) ?? null, + reactCompiler: Boolean(nextConfig.reactCompiler), + reactCompilerCompilationMode: typeof nextConfig.reactCompiler !== 'boolean' ? ((_nextConfig_reactCompiler = nextConfig.reactCompiler) == null ? void 0 : _nextConfig_reactCompiler.compilationMode) ?? null : null, + reactCompilerPanicThreshold: typeof nextConfig.reactCompiler !== 'boolean' ? ((_nextConfig_reactCompiler1 = nextConfig.reactCompiler) == null ? void 0 : _nextConfig_reactCompiler1.panicThreshold) ?? null : null, + adapterPath: !!(nextConfig == null ? void 0 : nextConfig.adapterPath) + }; + return [ + { + eventName: EVENT_VERSION, + payload + } + ]; +} + +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/events/version.js.map b/e-commerce/node_modules/next/dist/telemetry/events/version.js.map new file mode 100644 index 0000000000000000000000000000000000000000..80c3d3b7bc49ad3f63ebd1612952469c88ca80a0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/events/version.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/telemetry/events/version.ts"],"sourcesContent":["import type { NextConfigComplete } from '../../server/config-shared'\n\nconst EVENT_VERSION = 'NEXT_CLI_SESSION_STARTED'\n\ntype EventCliSessionStarted = {\n nextVersion: string\n nodeVersion: string\n cliCommand: string\n isSrcDir: boolean | null\n hasNowJson: boolean\n isCustomServer: boolean | null\n hasNextConfig: boolean\n buildTarget: string\n hasWebpackConfig: boolean\n hasBabelConfig: boolean\n basePathEnabled: boolean\n i18nEnabled: boolean\n imageEnabled: boolean\n imageFutureEnabled: boolean\n locales: string | null\n localeDomainsCount: number | null\n localeDetectionEnabled: boolean | null\n imageDomainsCount: number | null\n imageRemotePatternsCount: number | null\n imageLocalPatternsCount: number | null\n imageQualities: string | null\n imageSizes: string | null\n imageLoader: string | null\n imageFormats: string | null\n nextConfigOutput: string | null\n trailingSlashEnabled: boolean\n reactStrictMode: boolean\n webpackVersion: number | null\n turboFlag: boolean\n useTurbopackWorkerAssetPrefix: boolean\n isRspack: boolean\n appDir: boolean | null\n pagesDir: boolean | null\n staticStaleTime: number | null\n dynamicStaleTime: number | null\n reactCompiler: boolean\n reactCompilerCompilationMode: string | null\n reactCompilerPanicThreshold: string | null\n adapterPath: boolean\n}\n\nexport function eventCliSession(\n nextConfig: NextConfigComplete,\n event: Omit<\n EventCliSessionStarted,\n | 'nextVersion'\n | 'nodeVersion'\n | 'hasNextConfig'\n | 'buildTarget'\n | 'hasWebpackConfig'\n | 'hasBabelConfig'\n | 'basePathEnabled'\n | 'i18nEnabled'\n | 'imageEnabled'\n | 'imageFutureEnabled'\n | 'locales'\n | 'localeDomainsCount'\n | 'localeDetectionEnabled'\n | 'imageDomainsCount'\n | 'imageRemotePatternsCount'\n | 'imageLocalPatternsCount'\n | 'imageQualities'\n | 'imageSizes'\n | 'imageLoader'\n | 'imageFormats'\n | 'nextConfigOutput'\n | 'trailingSlashEnabled'\n | 'reactStrictMode'\n | 'staticStaleTime'\n | 'dynamicStaleTime'\n | 'reactCompiler'\n | 'reactCompilerCompilationMode'\n | 'reactCompilerPanicThreshold'\n | 'isRspack'\n | 'adapterPath'\n | 'useTurbopackWorkerAssetPrefix'\n >\n): { eventName: string; payload: EventCliSessionStarted }[] {\n // This should be an invariant, if it fails our build tooling is broken.\n if (typeof process.env.__NEXT_VERSION !== 'string') {\n return []\n }\n\n const { images, i18n } = nextConfig || {}\n\n const payload: EventCliSessionStarted = {\n nextVersion: process.env.__NEXT_VERSION,\n nodeVersion: process.version,\n cliCommand: event.cliCommand,\n isSrcDir: event.isSrcDir,\n hasNowJson: event.hasNowJson,\n isCustomServer: event.isCustomServer,\n hasNextConfig: nextConfig.configOrigin !== 'default',\n buildTarget: 'default',\n hasWebpackConfig: typeof nextConfig?.webpack === 'function',\n hasBabelConfig: false,\n imageEnabled: !!images,\n imageFutureEnabled: !!images,\n basePathEnabled: !!nextConfig?.basePath,\n i18nEnabled: !!i18n,\n locales: i18n?.locales ? i18n.locales.join(',') : null,\n localeDomainsCount: i18n?.domains ? i18n.domains.length : null,\n localeDetectionEnabled: !i18n ? null : i18n.localeDetection !== false,\n imageDomainsCount: images?.domains ? images.domains.length : null,\n imageRemotePatternsCount: images?.remotePatterns\n ? images.remotePatterns.length\n : null,\n imageLocalPatternsCount: images?.localPatterns\n ? images.localPatterns.length\n : null,\n imageSizes: images?.imageSizes ? images.imageSizes.join(',') : null,\n imageQualities: images?.qualities ? images.qualities.join(',') : null,\n imageLoader: images?.loader,\n imageFormats: images?.formats ? images.formats.join(',') : null,\n nextConfigOutput: nextConfig?.output || null,\n trailingSlashEnabled: !!nextConfig?.trailingSlash,\n reactStrictMode: !!nextConfig?.reactStrictMode,\n webpackVersion: event.webpackVersion || null,\n turboFlag: event.turboFlag || false,\n useTurbopackWorkerAssetPrefix:\n nextConfig?.experimental?.turbopackWorkerAssetPrefix !== undefined,\n isRspack: process.env.NEXT_RSPACK !== undefined,\n appDir: event.appDir,\n pagesDir: event.pagesDir,\n staticStaleTime: nextConfig.experimental.staleTimes?.static ?? null,\n dynamicStaleTime: nextConfig.experimental.staleTimes?.dynamic ?? null,\n reactCompiler: Boolean(nextConfig.reactCompiler),\n reactCompilerCompilationMode:\n typeof nextConfig.reactCompiler !== 'boolean'\n ? (nextConfig.reactCompiler?.compilationMode ?? null)\n : null,\n reactCompilerPanicThreshold:\n typeof nextConfig.reactCompiler !== 'boolean'\n ? (nextConfig.reactCompiler?.panicThreshold ?? null)\n : null,\n adapterPath: !!nextConfig?.adapterPath,\n }\n return [{ eventName: EVENT_VERSION, payload }]\n}\n"],"names":["eventCliSession","EVENT_VERSION","nextConfig","event","process","env","__NEXT_VERSION","images","i18n","payload","nextVersion","nodeVersion","version","cliCommand","isSrcDir","hasNowJson","isCustomServer","hasNextConfig","configOrigin","buildTarget","hasWebpackConfig","webpack","hasBabelConfig","imageEnabled","imageFutureEnabled","basePathEnabled","basePath","i18nEnabled","locales","join","localeDomainsCount","domains","length","localeDetectionEnabled","localeDetection","imageDomainsCount","imageRemotePatternsCount","remotePatterns","imageLocalPatternsCount","localPatterns","imageSizes","imageQualities","qualities","imageLoader","loader","imageFormats","formats","nextConfigOutput","output","trailingSlashEnabled","trailingSlash","reactStrictMode","webpackVersion","turboFlag","useTurbopackWorkerAssetPrefix","experimental","turbopackWorkerAssetPrefix","undefined","isRspack","NEXT_RSPACK","appDir","pagesDir","staticStaleTime","staleTimes","static","dynamicStaleTime","dynamic","reactCompiler","Boolean","reactCompilerCompilationMode","compilationMode","reactCompilerPanicThreshold","panicThreshold","adapterPath","eventName"],"mappings":";;;;+BA8CgBA;;;eAAAA;;;AA5ChB,MAAMC,gBAAgB;AA4Cf,SAASD,gBACdE,UAA8B,EAC9BC,KAiCC;QA4CGD,0BAIeA,qCACCA,sCAIXA,2BAIAA;IAvDT,wEAAwE;IACxE,IAAI,OAAOE,QAAQC,GAAG,CAACC,cAAc,KAAK,UAAU;QAClD,OAAO,EAAE;IACX;IAEA,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAE,GAAGN,cAAc,CAAC;IAExC,MAAMO,UAAkC;QACtCC,aAAaN,QAAQC,GAAG,CAACC,cAAc;QACvCK,aAAaP,QAAQQ,OAAO;QAC5BC,YAAYV,MAAMU,UAAU;QAC5BC,UAAUX,MAAMW,QAAQ;QACxBC,YAAYZ,MAAMY,UAAU;QAC5BC,gBAAgBb,MAAMa,cAAc;QACpCC,eAAef,WAAWgB,YAAY,KAAK;QAC3CC,aAAa;QACbC,kBAAkB,QAAOlB,8BAAAA,WAAYmB,OAAO,MAAK;QACjDC,gBAAgB;QAChBC,cAAc,CAAC,CAAChB;QAChBiB,oBAAoB,CAAC,CAACjB;QACtBkB,iBAAiB,CAAC,EAACvB,8BAAAA,WAAYwB,QAAQ;QACvCC,aAAa,CAAC,CAACnB;QACfoB,SAASpB,CAAAA,wBAAAA,KAAMoB,OAAO,IAAGpB,KAAKoB,OAAO,CAACC,IAAI,CAAC,OAAO;QAClDC,oBAAoBtB,CAAAA,wBAAAA,KAAMuB,OAAO,IAAGvB,KAAKuB,OAAO,CAACC,MAAM,GAAG;QAC1DC,wBAAwB,CAACzB,OAAO,OAAOA,KAAK0B,eAAe,KAAK;QAChEC,mBAAmB5B,CAAAA,0BAAAA,OAAQwB,OAAO,IAAGxB,OAAOwB,OAAO,CAACC,MAAM,GAAG;QAC7DI,0BAA0B7B,CAAAA,0BAAAA,OAAQ8B,cAAc,IAC5C9B,OAAO8B,cAAc,CAACL,MAAM,GAC5B;QACJM,yBAAyB/B,CAAAA,0BAAAA,OAAQgC,aAAa,IAC1ChC,OAAOgC,aAAa,CAACP,MAAM,GAC3B;QACJQ,YAAYjC,CAAAA,0BAAAA,OAAQiC,UAAU,IAAGjC,OAAOiC,UAAU,CAACX,IAAI,CAAC,OAAO;QAC/DY,gBAAgBlC,CAAAA,0BAAAA,OAAQmC,SAAS,IAAGnC,OAAOmC,SAAS,CAACb,IAAI,CAAC,OAAO;QACjEc,WAAW,EAAEpC,0BAAAA,OAAQqC,MAAM;QAC3BC,cAActC,CAAAA,0BAAAA,OAAQuC,OAAO,IAAGvC,OAAOuC,OAAO,CAACjB,IAAI,CAAC,OAAO;QAC3DkB,kBAAkB7C,CAAAA,8BAAAA,WAAY8C,MAAM,KAAI;QACxCC,sBAAsB,CAAC,EAAC/C,8BAAAA,WAAYgD,aAAa;QACjDC,iBAAiB,CAAC,EAACjD,8BAAAA,WAAYiD,eAAe;QAC9CC,gBAAgBjD,MAAMiD,cAAc,IAAI;QACxCC,WAAWlD,MAAMkD,SAAS,IAAI;QAC9BC,+BACEpD,CAAAA,+BAAAA,2BAAAA,WAAYqD,YAAY,qBAAxBrD,yBAA0BsD,0BAA0B,MAAKC;QAC3DC,UAAUtD,QAAQC,GAAG,CAACsD,WAAW,KAAKF;QACtCG,QAAQzD,MAAMyD,MAAM;QACpBC,UAAU1D,MAAM0D,QAAQ;QACxBC,iBAAiB5D,EAAAA,sCAAAA,WAAWqD,YAAY,CAACQ,UAAU,qBAAlC7D,oCAAoC8D,MAAM,KAAI;QAC/DC,kBAAkB/D,EAAAA,uCAAAA,WAAWqD,YAAY,CAACQ,UAAU,qBAAlC7D,qCAAoCgE,OAAO,KAAI;QACjEC,eAAeC,QAAQlE,WAAWiE,aAAa;QAC/CE,8BACE,OAAOnE,WAAWiE,aAAa,KAAK,YAC/BjE,EAAAA,4BAAAA,WAAWiE,aAAa,qBAAxBjE,0BAA0BoE,eAAe,KAAI,OAC9C;QACNC,6BACE,OAAOrE,WAAWiE,aAAa,KAAK,YAC/BjE,EAAAA,6BAAAA,WAAWiE,aAAa,qBAAxBjE,2BAA0BsE,cAAc,KAAI,OAC7C;QACNC,aAAa,CAAC,EAACvE,8BAAAA,WAAYuE,WAAW;IACxC;IACA,OAAO;QAAC;YAAEC,WAAWzE;YAAeQ;QAAQ;KAAE;AAChD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.d.ts b/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e400ae6487058a893afc400ee1c2987417ea69e3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.d.ts @@ -0,0 +1 @@ +export declare function flushTelemetry(): Promise; diff --git a/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.js b/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.js new file mode 100644 index 0000000000000000000000000000000000000000..b971445f43d0ececbc3a4d2ff66ee994edc193f6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "flushTelemetry", { + enumerable: true, + get: function() { + return flushTelemetry; + } +}); +const _shared = require("../trace/shared"); +async function flushTelemetry() { + let telemetry = _shared.traceGlobals.get('telemetry'); + if (telemetry) { + await telemetry.flush(); + } +} + +//# sourceMappingURL=flush-telemetry.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.js.map b/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5f1f0882aa058b7a2cc470132fa9529a6954cf8e --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/flush-telemetry.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/flush-telemetry.ts"],"sourcesContent":["import { traceGlobals } from '../trace/shared'\n\nexport async function flushTelemetry() {\n let telemetry = traceGlobals.get('telemetry') as\n | InstanceType\n | undefined\n if (telemetry) {\n await telemetry.flush()\n }\n}\n"],"names":["flushTelemetry","telemetry","traceGlobals","get","flush"],"mappings":";;;;+BAEsBA;;;eAAAA;;;wBAFO;AAEtB,eAAeA;IACpB,IAAIC,YAAYC,oBAAY,CAACC,GAAG,CAAC;IAGjC,IAAIF,WAAW;QACb,MAAMA,UAAUG,KAAK;IACvB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.d.ts b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ba9b209599361d2b4a09210830fd9ed5c850b65 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.d.ts @@ -0,0 +1,16 @@ +interface Payload { + meta: { + [key: string]: unknown; + }; + context: { + anonymousId: string; + projectId: string; + sessionId: string; + }; + events: Array<{ + eventName: string; + fields: object; + }>; +} +export declare function postNextTelemetryPayload(payload: Payload, signal?: any): any; +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.js b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.js new file mode 100644 index 0000000000000000000000000000000000000000..ff173fd6752e2480a0bcf767393925230a30451b --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "postNextTelemetryPayload", { + enumerable: true, + get: function() { + return postNextTelemetryPayload; + } +}); +const _asyncretry = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/async-retry")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function postNextTelemetryPayload(payload, signal) { + if (!signal && 'timeout' in AbortSignal) { + signal = AbortSignal.timeout(5000); + } + return (0, _asyncretry.default)(()=>fetch('https://telemetry.nextjs.org/api/v1/record', { + method: 'POST', + body: JSON.stringify(payload), + headers: { + 'content-type': 'application/json' + }, + signal + }).then((res)=>{ + if (!res.ok) { + const err = new Error(res.statusText); + err.response = res; + throw err; + } + }), { + minTimeout: 500, + retries: 1, + factor: 1 + }).catch(()=>{ + // We swallow errors when telemetry cannot be sent + })// Ensure promise is voided + .then(()=>{}, ()=>{}); +} + +//# sourceMappingURL=post-telemetry-payload.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.js.map b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e48f8fec43dcfa96fd5034b6b64900e1393eb29e --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/post-telemetry-payload.ts"],"sourcesContent":["import retry from 'next/dist/compiled/async-retry'\n\ninterface Payload {\n meta: { [key: string]: unknown }\n\n context: {\n anonymousId: string\n projectId: string\n sessionId: string\n }\n\n events: Array<{\n eventName: string\n fields: object\n }>\n}\n\nexport function postNextTelemetryPayload(payload: Payload, signal?: any) {\n if (!signal && 'timeout' in AbortSignal) {\n signal = AbortSignal.timeout(5000)\n }\n return (\n retry(\n () =>\n fetch('https://telemetry.nextjs.org/api/v1/record', {\n method: 'POST',\n body: JSON.stringify(payload),\n headers: { 'content-type': 'application/json' },\n signal,\n }).then((res) => {\n if (!res.ok) {\n const err = new Error(res.statusText)\n ;(err as any).response = res\n throw err\n }\n }),\n { minTimeout: 500, retries: 1, factor: 1 }\n )\n .catch(() => {\n // We swallow errors when telemetry cannot be sent\n })\n // Ensure promise is voided\n .then(\n () => {},\n () => {}\n )\n )\n}\n"],"names":["postNextTelemetryPayload","payload","signal","AbortSignal","timeout","retry","fetch","method","body","JSON","stringify","headers","then","res","ok","err","Error","statusText","response","minTimeout","retries","factor","catch"],"mappings":";;;;+BAiBgBA;;;eAAAA;;;mEAjBE;;;;;;AAiBX,SAASA,yBAAyBC,OAAgB,EAAEC,MAAY;IACrE,IAAI,CAACA,UAAU,aAAaC,aAAa;QACvCD,SAASC,YAAYC,OAAO,CAAC;IAC/B;IACA,OACEC,IAAAA,mBAAK,EACH,IACEC,MAAM,8CAA8C;YAClDC,QAAQ;YACRC,MAAMC,KAAKC,SAAS,CAACT;YACrBU,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CT;QACF,GAAGU,IAAI,CAAC,CAACC;YACP,IAAI,CAACA,IAAIC,EAAE,EAAE;gBACX,MAAMC,MAAM,IAAIC,MAAMH,IAAII,UAAU;gBAClCF,IAAYG,QAAQ,GAAGL;gBACzB,MAAME;YACR;QACF,IACF;QAAEI,YAAY;QAAKC,SAAS;QAAGC,QAAQ;IAAE,GAExCC,KAAK,CAAC;IACL,kDAAkD;IACpD,EACA,2BAA2B;KAC1BV,IAAI,CACH,KAAO,GACP,KAAO;AAGf","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.test.js b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6f08bf1afe2281bf42d79d2a86200f8a4891ebfe --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.test.js @@ -0,0 +1,83 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _posttelemetrypayload = require("./post-telemetry-payload"); +describe('postNextTelemetryPayload', ()=>{ + let originalFetch; + beforeEach(()=>{ + originalFetch = global.fetch; + }); + afterEach(()=>{ + global.fetch = originalFetch; + }); + it('sends telemetry payload successfully', async ()=>{ + const mockFetch = jest.fn().mockResolvedValue({ + ok: true + }); + global.fetch = mockFetch; + const payload = { + meta: { + version: '1.0' + }, + context: { + anonymousId: 'test-id', + projectId: 'test-project', + sessionId: 'test-session' + }, + events: [ + { + eventName: 'test-event', + fields: { + foo: 'bar' + } + } + ] + }; + await (0, _posttelemetrypayload.postNextTelemetryPayload)(payload); + expect(mockFetch).toHaveBeenCalledWith('https://telemetry.nextjs.org/api/v1/record', { + method: 'POST', + body: JSON.stringify(payload), + headers: { + 'content-type': 'application/json' + }, + signal: expect.any(AbortSignal) + }); + }); + it('retries on failure', async ()=>{ + const mockFetch = jest.fn().mockRejectedValueOnce(new Error('Network error')).mockResolvedValueOnce({ + ok: true + }); + global.fetch = mockFetch; + const payload = { + meta: {}, + context: { + anonymousId: 'test-id', + projectId: 'test-project', + sessionId: 'test-session' + }, + events: [] + }; + await (0, _posttelemetrypayload.postNextTelemetryPayload)(payload); + expect(mockFetch).toHaveBeenCalledTimes(2); + }); + it('swallows errors after retries exhausted', async ()=>{ + const mockFetch = jest.fn().mockRejectedValue(new Error('Network error')); + global.fetch = mockFetch; + const payload = { + meta: {}, + context: { + anonymousId: 'test-id', + projectId: 'test-project', + sessionId: 'test-session' + }, + events: [] + }; + // Should not throw + await (0, _posttelemetrypayload.postNextTelemetryPayload)(payload); + expect(mockFetch).toHaveBeenCalledTimes(2) // Initial try + 1 retry + ; + }); +}); + +//# sourceMappingURL=post-telemetry-payload.test.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.test.js.map b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.test.js.map new file mode 100644 index 0000000000000000000000000000000000000000..68232715edaddadf5d8dc11b5a986dcbf825af74 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/post-telemetry-payload.test.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/post-telemetry-payload.test.ts"],"sourcesContent":["import { postNextTelemetryPayload } from './post-telemetry-payload'\n\ndescribe('postNextTelemetryPayload', () => {\n let originalFetch: typeof fetch\n\n beforeEach(() => {\n originalFetch = global.fetch\n })\n\n afterEach(() => {\n global.fetch = originalFetch\n })\n\n it('sends telemetry payload successfully', async () => {\n const mockFetch = jest.fn().mockResolvedValue({\n ok: true,\n })\n global.fetch = mockFetch\n\n const payload = {\n meta: { version: '1.0' },\n context: {\n anonymousId: 'test-id',\n projectId: 'test-project',\n sessionId: 'test-session',\n },\n events: [\n {\n eventName: 'test-event',\n fields: { foo: 'bar' },\n },\n ],\n }\n\n await postNextTelemetryPayload(payload)\n\n expect(mockFetch).toHaveBeenCalledWith(\n 'https://telemetry.nextjs.org/api/v1/record',\n {\n method: 'POST',\n body: JSON.stringify(payload),\n headers: { 'content-type': 'application/json' },\n signal: expect.any(AbortSignal),\n }\n )\n })\n\n it('retries on failure', async () => {\n const mockFetch = jest\n .fn()\n .mockRejectedValueOnce(new Error('Network error'))\n .mockResolvedValueOnce({ ok: true })\n global.fetch = mockFetch\n\n const payload = {\n meta: {},\n context: {\n anonymousId: 'test-id',\n projectId: 'test-project',\n sessionId: 'test-session',\n },\n events: [],\n }\n\n await postNextTelemetryPayload(payload)\n\n expect(mockFetch).toHaveBeenCalledTimes(2)\n })\n\n it('swallows errors after retries exhausted', async () => {\n const mockFetch = jest.fn().mockRejectedValue(new Error('Network error'))\n global.fetch = mockFetch\n\n const payload = {\n meta: {},\n context: {\n anonymousId: 'test-id',\n projectId: 'test-project',\n sessionId: 'test-session',\n },\n events: [],\n }\n\n // Should not throw\n await postNextTelemetryPayload(payload)\n\n expect(mockFetch).toHaveBeenCalledTimes(2) // Initial try + 1 retry\n })\n})\n"],"names":["describe","originalFetch","beforeEach","global","fetch","afterEach","it","mockFetch","jest","fn","mockResolvedValue","ok","payload","meta","version","context","anonymousId","projectId","sessionId","events","eventName","fields","foo","postNextTelemetryPayload","expect","toHaveBeenCalledWith","method","body","JSON","stringify","headers","signal","any","AbortSignal","mockRejectedValueOnce","Error","mockResolvedValueOnce","toHaveBeenCalledTimes","mockRejectedValue"],"mappings":";;;;sCAAyC;AAEzCA,SAAS,4BAA4B;IACnC,IAAIC;IAEJC,WAAW;QACTD,gBAAgBE,OAAOC,KAAK;IAC9B;IAEAC,UAAU;QACRF,OAAOC,KAAK,GAAGH;IACjB;IAEAK,GAAG,wCAAwC;QACzC,MAAMC,YAAYC,KAAKC,EAAE,GAAGC,iBAAiB,CAAC;YAC5CC,IAAI;QACN;QACAR,OAAOC,KAAK,GAAGG;QAEf,MAAMK,UAAU;YACdC,MAAM;gBAAEC,SAAS;YAAM;YACvBC,SAAS;gBACPC,aAAa;gBACbC,WAAW;gBACXC,WAAW;YACb;YACAC,QAAQ;gBACN;oBACEC,WAAW;oBACXC,QAAQ;wBAAEC,KAAK;oBAAM;gBACvB;aACD;QACH;QAEA,MAAMC,IAAAA,8CAAwB,EAACX;QAE/BY,OAAOjB,WAAWkB,oBAAoB,CACpC,8CACA;YACEC,QAAQ;YACRC,MAAMC,KAAKC,SAAS,CAACjB;YACrBkB,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CC,QAAQP,OAAOQ,GAAG,CAACC;QACrB;IAEJ;IAEA3B,GAAG,sBAAsB;QACvB,MAAMC,YAAYC,KACfC,EAAE,GACFyB,qBAAqB,CAAC,IAAIC,MAAM,kBAChCC,qBAAqB,CAAC;YAAEzB,IAAI;QAAK;QACpCR,OAAOC,KAAK,GAAGG;QAEf,MAAMK,UAAU;YACdC,MAAM,CAAC;YACPE,SAAS;gBACPC,aAAa;gBACbC,WAAW;gBACXC,WAAW;YACb;YACAC,QAAQ,EAAE;QACZ;QAEA,MAAMI,IAAAA,8CAAwB,EAACX;QAE/BY,OAAOjB,WAAW8B,qBAAqB,CAAC;IAC1C;IAEA/B,GAAG,2CAA2C;QAC5C,MAAMC,YAAYC,KAAKC,EAAE,GAAG6B,iBAAiB,CAAC,IAAIH,MAAM;QACxDhC,OAAOC,KAAK,GAAGG;QAEf,MAAMK,UAAU;YACdC,MAAM,CAAC;YACPE,SAAS;gBACPC,aAAa;gBACbC,WAAW;gBACXC,WAAW;YACb;YACAC,QAAQ,EAAE;QACZ;QAEA,mBAAmB;QACnB,MAAMI,IAAAA,8CAAwB,EAACX;QAE/BY,OAAOjB,WAAW8B,qBAAqB,CAAC,GAAG,wBAAwB;;IACrE;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/project-id.d.ts b/e-commerce/node_modules/next/dist/telemetry/project-id.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b257f649021a72652773a75fcf25125e65fee46 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/project-id.d.ts @@ -0,0 +1 @@ +export declare function getRawProjectId(): Promise; diff --git a/e-commerce/node_modules/next/dist/telemetry/project-id.js b/e-commerce/node_modules/next/dist/telemetry/project-id.js new file mode 100644 index 0000000000000000000000000000000000000000..16712385c5db16f2e00af86e597a80a857f358af --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/project-id.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getRawProjectId", { + enumerable: true, + get: function() { + return getRawProjectId; + } +}); +const _child_process = require("child_process"); +// Q: Why does Next.js need a project ID? Why is it looking at my git remote? +// A: +// Next.js' telemetry is and always will be completely anonymous. Because of +// this, we need a way to differentiate different projects to track feature +// usage accurately. For example, to prevent a feature from appearing to be +// constantly `used` and then `unused` when switching between local projects. +// To reiterate, +// we **never** can read your actual git remote. The value is hashed one-way +// with random salt data, making it impossible for us to reverse or try to +// guess the remote by re-computing hashes. +async function _getProjectIdByGit() { + try { + let resolve, reject; + const promise = new Promise((res, rej)=>{ + resolve = res; + reject = rej; + }); + (0, _child_process.exec)(`git config --local --get remote.origin.url`, { + timeout: 1000, + windowsHide: true + }, (error, stdout)=>{ + if (error) { + reject(error); + return; + } + resolve(stdout); + }); + return String(await promise).trim(); + } catch (_) { + return null; + } +} +async function getRawProjectId() { + return await _getProjectIdByGit() || process.env.REPOSITORY_URL || process.cwd(); +} + +//# sourceMappingURL=project-id.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/project-id.js.map b/e-commerce/node_modules/next/dist/telemetry/project-id.js.map new file mode 100644 index 0000000000000000000000000000000000000000..13995a58651c34f18946a3574483750ffa277954 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/project-id.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/project-id.ts"],"sourcesContent":["import { exec } from 'child_process'\n\n// Q: Why does Next.js need a project ID? Why is it looking at my git remote?\n// A:\n// Next.js' telemetry is and always will be completely anonymous. Because of\n// this, we need a way to differentiate different projects to track feature\n// usage accurately. For example, to prevent a feature from appearing to be\n// constantly `used` and then `unused` when switching between local projects.\n// To reiterate,\n// we **never** can read your actual git remote. The value is hashed one-way\n// with random salt data, making it impossible for us to reverse or try to\n// guess the remote by re-computing hashes.\n\nasync function _getProjectIdByGit() {\n try {\n let resolve: (value: Buffer | string) => void, reject: (err: Error) => void\n const promise = new Promise((res, rej) => {\n resolve = res\n reject = rej\n })\n\n exec(\n `git config --local --get remote.origin.url`,\n {\n timeout: 1000,\n windowsHide: true,\n },\n (error: null | Error, stdout: Buffer | string) => {\n if (error) {\n reject(error)\n return\n }\n resolve(stdout)\n }\n )\n\n return String(await promise).trim()\n } catch (_) {\n return null\n }\n}\n\nexport async function getRawProjectId(): Promise {\n return (\n (await _getProjectIdByGit()) || process.env.REPOSITORY_URL || process.cwd()\n )\n}\n"],"names":["getRawProjectId","_getProjectIdByGit","resolve","reject","promise","Promise","res","rej","exec","timeout","windowsHide","error","stdout","String","trim","_","process","env","REPOSITORY_URL","cwd"],"mappings":";;;;+BA0CsBA;;;eAAAA;;;+BA1CD;AAErB,6EAA6E;AAC7E,KAAK;AACL,4EAA4E;AAC5E,2EAA2E;AAC3E,2EAA2E;AAC3E,6EAA6E;AAC7E,gBAAgB;AAChB,4EAA4E;AAC5E,0EAA0E;AAC1E,2CAA2C;AAE3C,eAAeC;IACb,IAAI;QACF,IAAIC,SAA2CC;QAC/C,MAAMC,UAAU,IAAIC,QAAyB,CAACC,KAAKC;YACjDL,UAAUI;YACVH,SAASI;QACX;QAEAC,IAAAA,mBAAI,EACF,CAAC,0CAA0C,CAAC,EAC5C;YACEC,SAAS;YACTC,aAAa;QACf,GACA,CAACC,OAAqBC;YACpB,IAAID,OAAO;gBACTR,OAAOQ;gBACP;YACF;YACAT,QAAQU;QACV;QAGF,OAAOC,OAAO,MAAMT,SAASU,IAAI;IACnC,EAAE,OAAOC,GAAG;QACV,OAAO;IACT;AACF;AAEO,eAAef;IACpB,OACE,AAAC,MAAMC,wBAAyBe,QAAQC,GAAG,CAACC,cAAc,IAAIF,QAAQG,GAAG;AAE7E","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/storage.d.ts b/e-commerce/node_modules/next/dist/telemetry/storage.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7eb7324e23af587bb2a2c141ed8fcfb88f34b6d --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/storage.d.ts @@ -0,0 +1,42 @@ +import type { BinaryLike } from 'crypto'; +export type TelemetryEvent = { + eventName: string; + payload: object; +}; +type RecordObject = { + isFulfilled: boolean; + isRejected: boolean; + value?: any; + reason?: any; +}; +export declare class Telemetry { + readonly sessionId: string; + private conf; + private distDir; + private loadProjectId; + private NEXT_TELEMETRY_DISABLED; + private NEXT_TELEMETRY_DEBUG; + private queue; + constructor({ distDir, skipNotify, }: { + distDir: string; + skipNotify?: boolean; + }); + private notify; + get anonymousId(): string; + get salt(): string; + private get isDisabled(); + setEnabled: (_enabled: boolean) => string | null; + get isEnabled(): boolean; + oneWayHash: (payload: BinaryLike) => string; + private getProjectId; + record: (_events: TelemetryEvent | TelemetryEvent[], deferred?: boolean) => Promise; + flush: () => Promise; + flushDetached: ({ mode, dir, distDir, events, }: { + mode: "dev"; + dir: string; + distDir: string | null; + events: TelemetryEvent[] | null; + }) => void; + private submitRecord; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/telemetry/storage.js b/e-commerce/node_modules/next/dist/telemetry/storage.js new file mode 100644 index 0000000000000000000000000000000000000000..ba404888c825ff94c670869a87a830a19c3fea86 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/storage.js @@ -0,0 +1,317 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Telemetry", { + enumerable: true, + get: function() { + return Telemetry; + } +}); +const _picocolors = require("../lib/picocolors"); +const _conf = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/conf")); +const _crypto = require("crypto"); +const _isdocker = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/is-docker")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _anonymousmeta = require("./anonymous-meta"); +const _ciinfo = /*#__PURE__*/ _interop_require_wildcard(require("../server/ci-info")); +const _posttelemetrypayload = require("./post-telemetry-payload"); +const _projectid = require("./project-id"); +const _ponyfill = require("next/dist/compiled/@edge-runtime/ponyfill"); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +// This is the key that stores whether or not telemetry is enabled or disabled. +const TELEMETRY_KEY_ENABLED = 'telemetry.enabled'; +// This is the key that specifies when the user was informed about anonymous +// telemetry collection. +const TELEMETRY_KEY_NOTIFY_DATE = 'telemetry.notifiedAt'; +// This is a quasi-persistent identifier used to dedupe recurring events. It's +// generated from random data and completely anonymous. +const TELEMETRY_KEY_ID = `telemetry.anonymousId`; +// This is the cryptographic salt that is included within every hashed value. +// This salt value is never sent to us, ensuring privacy and the one-way nature +// of the hash (prevents dictionary lookups of pre-computed hashes). +// See the `oneWayHash` function. +const TELEMETRY_KEY_SALT = `telemetry.salt`; +function getStorageDirectory(distDir) { + const isLikelyEphemeral = _ciinfo.isCI || (0, _isdocker.default)(); + if (isLikelyEphemeral) { + return _path.default.join(distDir, 'cache'); + } + return undefined; +} +class Telemetry { + constructor({ distDir, skipNotify = false }){ + this.notify = ()=>{ + if (this.isDisabled || !this.conf) { + return; + } + // The end-user has already been notified about our telemetry integration. We + // don't need to constantly annoy them about it. + // We will re-inform users about the telemetry if significant changes are + // ever made. + if (this.conf.get(TELEMETRY_KEY_NOTIFY_DATE, '')) { + return; + } + this.conf.set(TELEMETRY_KEY_NOTIFY_DATE, Date.now().toString()); + console.log(`${(0, _picocolors.magenta)((0, _picocolors.bold)('Attention'))}: Next.js now collects completely anonymous telemetry regarding usage.`); + console.log(`This information is used to shape Next.js' roadmap and prioritize features.`); + console.log(`You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:`); + console.log((0, _picocolors.cyan)('https://nextjs.org/telemetry')); + console.log(); + }; + this.setEnabled = (_enabled)=>{ + const enabled = !!_enabled; + this.conf && this.conf.set(TELEMETRY_KEY_ENABLED, enabled); + return this.conf && this.conf.path; + }; + this.oneWayHash = (payload)=>{ + const hash = (0, _crypto.createHash)('sha256'); + // Always prepend the payload value with salt. This ensures the hash is truly + // one-way. + hash.update(this.salt); + // Update is an append operation, not a replacement. The salt from the prior + // update is still present! + hash.update(payload); + return hash.digest('hex'); + }; + this.record = (_events, deferred)=>{ + const prom = (deferred ? // flushDetached we can skip starting the initial + // submitRecord which will then be cancelled + new Promise((resolve)=>resolve({ + isFulfilled: true, + isRejected: false, + value: _events + })) : this.submitRecord(_events)).then((value)=>({ + isFulfilled: true, + isRejected: false, + value + })).catch((reason)=>({ + isFulfilled: false, + isRejected: true, + reason + }))// Acts as `Promise#finally` because `catch` transforms the error + .then((res)=>{ + // Clean up the event to prevent unbounded `Set` growth + if (!deferred) { + this.queue.delete(prom); + } + return res; + }); + prom._events = Array.isArray(_events) ? _events : [ + _events + ]; + prom._controller = prom._controller; + // Track this `Promise` so we can flush pending events + this.queue.add(prom); + return prom; + }; + this.flush = async ()=>{ + return Promise.all(this.queue).catch(()=>null); + }; + // writes current events to disk and spawns separate + // detached process to submit the records without blocking + // the main process from exiting + this.flushDetached = ({ mode, dir, distDir, events })=>{ + // Nudges detach only their own events; shutdown flushes the full queue. + const allEvents = events ?? []; + if (events === null) { + this.queue.forEach((item)=>{ + try { + var _item__controller; + (_item__controller = item._controller) == null ? void 0 : _item__controller.abort(); + allEvents.push(...item._events); + } catch (_) { + // if we fail to abort ignore this event + } + }); + } + if (allEvents.length === 0) { + // No events to flush + return; + } + // Builds preserve cache while cleaning distDir, so detached batches survive cleanup. + const eventsDirectory = _path.default.join(this.distDir, 'cache'); + _fs.default.mkdirSync(eventsDirectory, { + recursive: true + }); + // Each flush owns its file so a later shutdown flush cannot replace a nudge batch. + const eventsFile = `_events_${process.pid}_${(0, _crypto.randomBytes)(8).toString('hex')}.json`; + _fs.default.writeFileSync(_path.default.join(eventsDirectory, eventsFile), JSON.stringify(allEvents)); + // Note: cross-spawn is not used here as it causes + // a new command window to appear when we don't want it to + const child_process = require('child_process'); + // we use spawnSync when debugging to ensure logs are piped + // correctly to stdout/stderr + const spawn = this.NEXT_TELEMETRY_DEBUG ? child_process.spawnSync : child_process.spawn; + spawn(process.execPath, [ + require.resolve('./detached-flush'), + mode, + dir, + eventsFile, + ...distDir ? [ + distDir + ] : [] + ], { + detached: !this.NEXT_TELEMETRY_DEBUG, + windowsHide: true, + shell: false, + ...this.NEXT_TELEMETRY_DEBUG ? { + stdio: 'inherit' + } : {} + }); + }; + this.submitRecord = async (_events)=>{ + let events; + if (Array.isArray(_events)) { + events = _events; + } else { + events = [ + _events + ]; + } + if (events.length < 1) { + return Promise.resolve(); + } + if (this.NEXT_TELEMETRY_DEBUG) { + // Resolve the anonymous meta so the debug output mirrors the payload that + // would be sent (including `agentName`, `ciName`, etc.). + const meta = await (0, _anonymousmeta.getAnonymousMeta)(); + // Return a promise that resolves after logging to ensure the output + // is captured before the process exits (e.g., during flushDetached) + return new Promise((resolve)=>{ + setTimeout(()=>{ + // Print to standard error to simplify selecting the output + events.forEach(({ eventName, payload })=>console.error(`[telemetry] ` + JSON.stringify({ + eventName, + payload, + meta + }, null, 2))); + resolve(undefined); + }, 100); + }); + } + // Skip recording telemetry if the feature is disabled + if (this.isDisabled) { + return Promise.resolve(); + } + const postController = new _ponyfill.AbortController(); + const res = (0, _posttelemetrypayload.postNextTelemetryPayload)({ + context: { + anonymousId: this.anonymousId, + projectId: await this.getProjectId(), + sessionId: this.sessionId + }, + meta: await (0, _anonymousmeta.getAnonymousMeta)(), + events: events.map(({ eventName, payload })=>({ + eventName, + fields: payload + })) + }, postController.signal); + // Bound delivery even when callers await record/flush; retries share this deadline. + const timeout = setTimeout(()=>postController.abort(), 5000); + res._controller = postController; + return res.finally(()=>clearTimeout(timeout)); + }; + // Read in the constructor so that .env can be loaded before reading + const { NEXT_TELEMETRY_DISABLED, NEXT_TELEMETRY_DEBUG } = process.env; + this.NEXT_TELEMETRY_DISABLED = NEXT_TELEMETRY_DISABLED; + this.NEXT_TELEMETRY_DEBUG = NEXT_TELEMETRY_DEBUG; + this.distDir = distDir; + const storageDirectory = getStorageDirectory(distDir); + try { + // `conf` incorrectly throws a permission error during initialization + // instead of waiting for first use. We need to handle it, otherwise the + // process may crash. + this.conf = new _conf.default({ + projectName: 'nextjs', + cwd: storageDirectory + }); + } catch (_) { + this.conf = null; + } + this.sessionId = (0, _crypto.randomBytes)(32).toString('hex'); + this.queue = new Set(); + if (!skipNotify) { + this.notify(); + } + } + get anonymousId() { + const val = this.conf && this.conf.get(TELEMETRY_KEY_ID); + if (val) { + return val; + } + const generated = (0, _crypto.randomBytes)(32).toString('hex'); + this.conf && this.conf.set(TELEMETRY_KEY_ID, generated); + return generated; + } + get salt() { + const val = this.conf && this.conf.get(TELEMETRY_KEY_SALT); + if (val) { + return val; + } + const generated = (0, _crypto.randomBytes)(16).toString('hex'); + this.conf && this.conf.set(TELEMETRY_KEY_SALT, generated); + return generated; + } + get isDisabled() { + if (!!this.NEXT_TELEMETRY_DISABLED || !this.conf) { + return true; + } + return this.conf.get(TELEMETRY_KEY_ENABLED, true) === false; + } + get isEnabled() { + return !this.NEXT_TELEMETRY_DISABLED && !!this.conf && this.conf.get(TELEMETRY_KEY_ENABLED, true) !== false; + } + async getProjectId() { + this.loadProjectId = this.loadProjectId || (0, _projectid.getRawProjectId)(); + return this.oneWayHash(await this.loadProjectId); + } +} + +//# sourceMappingURL=storage.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/telemetry/storage.js.map b/e-commerce/node_modules/next/dist/telemetry/storage.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d6c18d395770f0e179d9ba1ec613909b07869f70 --- /dev/null +++ b/e-commerce/node_modules/next/dist/telemetry/storage.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/telemetry/storage.ts"],"sourcesContent":["import type { BinaryLike } from 'crypto'\nimport { bold, cyan, magenta } from '../lib/picocolors'\nimport Conf from 'next/dist/compiled/conf'\nimport { createHash, randomBytes } from 'crypto'\nimport isDockerFunction from 'next/dist/compiled/is-docker'\nimport path from 'path'\n\nimport { getAnonymousMeta } from './anonymous-meta'\nimport * as ciEnvironment from '../server/ci-info'\nimport { postNextTelemetryPayload } from './post-telemetry-payload'\nimport { getRawProjectId } from './project-id'\nimport { AbortController } from 'next/dist/compiled/@edge-runtime/ponyfill'\nimport fs from 'fs'\n\n// This is the key that stores whether or not telemetry is enabled or disabled.\nconst TELEMETRY_KEY_ENABLED = 'telemetry.enabled'\n\n// This is the key that specifies when the user was informed about anonymous\n// telemetry collection.\nconst TELEMETRY_KEY_NOTIFY_DATE = 'telemetry.notifiedAt'\n\n// This is a quasi-persistent identifier used to dedupe recurring events. It's\n// generated from random data and completely anonymous.\nconst TELEMETRY_KEY_ID = `telemetry.anonymousId`\n\n// This is the cryptographic salt that is included within every hashed value.\n// This salt value is never sent to us, ensuring privacy and the one-way nature\n// of the hash (prevents dictionary lookups of pre-computed hashes).\n// See the `oneWayHash` function.\nconst TELEMETRY_KEY_SALT = `telemetry.salt`\n\nexport type TelemetryEvent = { eventName: string; payload: object }\n\ntype RecordObject = {\n isFulfilled: boolean\n isRejected: boolean\n value?: any\n reason?: any\n}\n\nfunction getStorageDirectory(distDir: string): string | undefined {\n const isLikelyEphemeral = ciEnvironment.isCI || isDockerFunction()\n\n if (isLikelyEphemeral) {\n return path.join(distDir, 'cache')\n }\n\n return undefined\n}\n\nexport class Telemetry {\n readonly sessionId: string\n\n private conf: Conf | null\n private distDir: string\n private loadProjectId: undefined | string | Promise\n private NEXT_TELEMETRY_DISABLED: any\n private NEXT_TELEMETRY_DEBUG: any\n\n private queue: Set>\n\n constructor({\n distDir,\n skipNotify = false,\n }: {\n distDir: string\n skipNotify?: boolean\n }) {\n // Read in the constructor so that .env can be loaded before reading\n const { NEXT_TELEMETRY_DISABLED, NEXT_TELEMETRY_DEBUG } = process.env\n this.NEXT_TELEMETRY_DISABLED = NEXT_TELEMETRY_DISABLED\n this.NEXT_TELEMETRY_DEBUG = NEXT_TELEMETRY_DEBUG\n this.distDir = distDir\n const storageDirectory = getStorageDirectory(distDir)\n\n try {\n // `conf` incorrectly throws a permission error during initialization\n // instead of waiting for first use. We need to handle it, otherwise the\n // process may crash.\n this.conf = new Conf({ projectName: 'nextjs', cwd: storageDirectory })\n } catch (_) {\n this.conf = null\n }\n this.sessionId = randomBytes(32).toString('hex')\n this.queue = new Set()\n\n if (!skipNotify) {\n this.notify()\n }\n }\n\n private notify = () => {\n if (this.isDisabled || !this.conf) {\n return\n }\n\n // The end-user has already been notified about our telemetry integration. We\n // don't need to constantly annoy them about it.\n // We will re-inform users about the telemetry if significant changes are\n // ever made.\n if (this.conf.get(TELEMETRY_KEY_NOTIFY_DATE, '')) {\n return\n }\n this.conf.set(TELEMETRY_KEY_NOTIFY_DATE, Date.now().toString())\n\n console.log(\n `${magenta(\n bold('Attention')\n )}: Next.js now collects completely anonymous telemetry regarding usage.`\n )\n console.log(\n `This information is used to shape Next.js' roadmap and prioritize features.`\n )\n console.log(\n `You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:`\n )\n console.log(cyan('https://nextjs.org/telemetry'))\n console.log()\n }\n\n get anonymousId(): string {\n const val = this.conf && this.conf.get(TELEMETRY_KEY_ID)\n if (val) {\n return val\n }\n\n const generated = randomBytes(32).toString('hex')\n this.conf && this.conf.set(TELEMETRY_KEY_ID, generated)\n return generated\n }\n\n get salt(): string {\n const val = this.conf && this.conf.get(TELEMETRY_KEY_SALT)\n if (val) {\n return val\n }\n\n const generated = randomBytes(16).toString('hex')\n this.conf && this.conf.set(TELEMETRY_KEY_SALT, generated)\n return generated\n }\n\n private get isDisabled(): boolean {\n if (!!this.NEXT_TELEMETRY_DISABLED || !this.conf) {\n return true\n }\n return this.conf.get(TELEMETRY_KEY_ENABLED, true) === false\n }\n\n setEnabled = (_enabled: boolean) => {\n const enabled = !!_enabled\n this.conf && this.conf.set(TELEMETRY_KEY_ENABLED, enabled)\n return this.conf && this.conf.path\n }\n\n get isEnabled(): boolean {\n return (\n !this.NEXT_TELEMETRY_DISABLED &&\n !!this.conf &&\n this.conf.get(TELEMETRY_KEY_ENABLED, true) !== false\n )\n }\n\n oneWayHash = (payload: BinaryLike): string => {\n const hash = createHash('sha256')\n\n // Always prepend the payload value with salt. This ensures the hash is truly\n // one-way.\n hash.update(this.salt)\n\n // Update is an append operation, not a replacement. The salt from the prior\n // update is still present!\n hash.update(payload)\n return hash.digest('hex')\n }\n\n private async getProjectId(): Promise {\n this.loadProjectId = this.loadProjectId || getRawProjectId()\n return this.oneWayHash(await this.loadProjectId)\n }\n\n record = (\n _events: TelemetryEvent | TelemetryEvent[],\n deferred?: boolean\n ): Promise => {\n const prom = (\n deferred\n ? // if we know we are going to immediately call\n // flushDetached we can skip starting the initial\n // submitRecord which will then be cancelled\n new Promise((resolve) =>\n resolve({\n isFulfilled: true,\n isRejected: false,\n value: _events,\n })\n )\n : this.submitRecord(_events)\n )\n .then((value) => ({\n isFulfilled: true,\n isRejected: false,\n value,\n }))\n .catch((reason) => ({\n isFulfilled: false,\n isRejected: true,\n reason,\n }))\n // Acts as `Promise#finally` because `catch` transforms the error\n .then((res) => {\n // Clean up the event to prevent unbounded `Set` growth\n if (!deferred) {\n this.queue.delete(prom)\n }\n return res\n })\n\n ;(prom as any)._events = Array.isArray(_events) ? _events : [_events]\n ;(prom as any)._controller = (prom as any)._controller\n // Track this `Promise` so we can flush pending events\n this.queue.add(prom)\n\n return prom\n }\n\n flush = async () => {\n return Promise.all(this.queue).catch(() => null)\n }\n\n // writes current events to disk and spawns separate\n // detached process to submit the records without blocking\n // the main process from exiting\n flushDetached = ({\n mode,\n dir,\n distDir,\n events,\n }: {\n mode: 'dev'\n dir: string\n distDir: string | null\n events: TelemetryEvent[] | null\n }) => {\n // Nudges detach only their own events; shutdown flushes the full queue.\n const allEvents: TelemetryEvent[] = events ?? []\n\n if (events === null) {\n this.queue.forEach((item: any) => {\n try {\n item._controller?.abort()\n allEvents.push(...item._events)\n } catch (_) {\n // if we fail to abort ignore this event\n }\n })\n }\n\n if (allEvents.length === 0) {\n // No events to flush\n return\n }\n\n // Builds preserve cache while cleaning distDir, so detached batches survive cleanup.\n const eventsDirectory = path.join(this.distDir, 'cache')\n fs.mkdirSync(eventsDirectory, { recursive: true })\n // Each flush owns its file so a later shutdown flush cannot replace a nudge batch.\n const eventsFile = `_events_${process.pid}_${randomBytes(8).toString('hex')}.json`\n fs.writeFileSync(\n path.join(eventsDirectory, eventsFile),\n JSON.stringify(allEvents)\n )\n\n // Note: cross-spawn is not used here as it causes\n // a new command window to appear when we don't want it to\n const child_process =\n require('child_process') as typeof import('child_process')\n\n // we use spawnSync when debugging to ensure logs are piped\n // correctly to stdout/stderr\n const spawn = this.NEXT_TELEMETRY_DEBUG\n ? child_process.spawnSync\n : child_process.spawn\n\n spawn(\n process.execPath,\n [\n require.resolve('./detached-flush'),\n mode,\n dir,\n eventsFile,\n ...(distDir ? [distDir] : []),\n ],\n {\n detached: !this.NEXT_TELEMETRY_DEBUG,\n windowsHide: true,\n shell: false,\n ...(this.NEXT_TELEMETRY_DEBUG\n ? {\n stdio: 'inherit',\n }\n : {}),\n }\n )\n }\n\n private submitRecord = async (\n _events: TelemetryEvent | TelemetryEvent[]\n ): Promise => {\n let events: TelemetryEvent[]\n if (Array.isArray(_events)) {\n events = _events\n } else {\n events = [_events]\n }\n\n if (events.length < 1) {\n return Promise.resolve()\n }\n\n if (this.NEXT_TELEMETRY_DEBUG) {\n // Resolve the anonymous meta so the debug output mirrors the payload that\n // would be sent (including `agentName`, `ciName`, etc.).\n const meta = await getAnonymousMeta()\n // Return a promise that resolves after logging to ensure the output\n // is captured before the process exits (e.g., during flushDetached)\n return new Promise((resolve) => {\n setTimeout(() => {\n // Print to standard error to simplify selecting the output\n events.forEach(({ eventName, payload }) =>\n console.error(\n `[telemetry] ` +\n JSON.stringify({ eventName, payload, meta }, null, 2)\n )\n )\n resolve(undefined)\n }, 100)\n })\n }\n\n // Skip recording telemetry if the feature is disabled\n if (this.isDisabled) {\n return Promise.resolve()\n }\n\n const postController = new AbortController()\n const res = postNextTelemetryPayload(\n {\n context: {\n anonymousId: this.anonymousId,\n projectId: await this.getProjectId(),\n sessionId: this.sessionId,\n },\n meta: await getAnonymousMeta(),\n events: events.map(({ eventName, payload }) => ({\n eventName,\n fields: payload,\n })),\n },\n postController.signal\n )\n // Bound delivery even when callers await record/flush; retries share this deadline.\n const timeout = setTimeout(() => postController.abort(), 5000)\n res._controller = postController\n return res.finally(() => clearTimeout(timeout))\n }\n}\n"],"names":["Telemetry","TELEMETRY_KEY_ENABLED","TELEMETRY_KEY_NOTIFY_DATE","TELEMETRY_KEY_ID","TELEMETRY_KEY_SALT","getStorageDirectory","distDir","isLikelyEphemeral","ciEnvironment","isCI","isDockerFunction","path","join","undefined","constructor","skipNotify","notify","isDisabled","conf","get","set","Date","now","toString","console","log","magenta","bold","cyan","setEnabled","_enabled","enabled","oneWayHash","payload","hash","createHash","update","salt","digest","record","_events","deferred","prom","Promise","resolve","isFulfilled","isRejected","value","submitRecord","then","catch","reason","res","queue","delete","Array","isArray","_controller","add","flush","all","flushDetached","mode","dir","events","allEvents","forEach","item","abort","push","_","length","eventsDirectory","fs","mkdirSync","recursive","eventsFile","process","pid","randomBytes","writeFileSync","JSON","stringify","child_process","require","spawn","NEXT_TELEMETRY_DEBUG","spawnSync","execPath","detached","windowsHide","shell","stdio","meta","getAnonymousMeta","setTimeout","eventName","error","postController","AbortController","postNextTelemetryPayload","context","anonymousId","projectId","getProjectId","sessionId","map","fields","signal","timeout","finally","clearTimeout","NEXT_TELEMETRY_DISABLED","env","storageDirectory","Conf","projectName","cwd","Set","val","generated","isEnabled","loadProjectId","getRawProjectId"],"mappings":";;;;+BAkDaA;;;eAAAA;;;4BAjDuB;6DACnB;wBACuB;iEACX;6DACZ;+BAEgB;gEACF;sCACU;2BACT;0BACA;2DACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEf,+EAA+E;AAC/E,MAAMC,wBAAwB;AAE9B,4EAA4E;AAC5E,wBAAwB;AACxB,MAAMC,4BAA4B;AAElC,8EAA8E;AAC9E,uDAAuD;AACvD,MAAMC,mBAAmB,CAAC,qBAAqB,CAAC;AAEhD,6EAA6E;AAC7E,+EAA+E;AAC/E,oEAAoE;AACpE,iCAAiC;AACjC,MAAMC,qBAAqB,CAAC,cAAc,CAAC;AAW3C,SAASC,oBAAoBC,OAAe;IAC1C,MAAMC,oBAAoBC,QAAcC,IAAI,IAAIC,IAAAA,iBAAgB;IAEhE,IAAIH,mBAAmB;QACrB,OAAOI,aAAI,CAACC,IAAI,CAACN,SAAS;IAC5B;IAEA,OAAOO;AACT;AAEO,MAAMb;IAWXc,YAAY,EACVR,OAAO,EACPS,aAAa,KAAK,EAInB,CAAE;aAwBKC,SAAS;YACf,IAAI,IAAI,CAACC,UAAU,IAAI,CAAC,IAAI,CAACC,IAAI,EAAE;gBACjC;YACF;YAEA,6EAA6E;YAC7E,gDAAgD;YAChD,yEAAyE;YACzE,aAAa;YACb,IAAI,IAAI,CAACA,IAAI,CAACC,GAAG,CAACjB,2BAA2B,KAAK;gBAChD;YACF;YACA,IAAI,CAACgB,IAAI,CAACE,GAAG,CAAClB,2BAA2BmB,KAAKC,GAAG,GAAGC,QAAQ;YAE5DC,QAAQC,GAAG,CACT,GAAGC,IAAAA,mBAAO,EACRC,IAAAA,gBAAI,EAAC,cACL,sEAAsE,CAAC;YAE3EH,QAAQC,GAAG,CACT,CAAC,2EAA2E,CAAC;YAE/ED,QAAQC,GAAG,CACT,CAAC,uIAAuI,CAAC;YAE3ID,QAAQC,GAAG,CAACG,IAAAA,gBAAI,EAAC;YACjBJ,QAAQC,GAAG;QACb;aA+BAI,aAAa,CAACC;YACZ,MAAMC,UAAU,CAAC,CAACD;YAClB,IAAI,CAACZ,IAAI,IAAI,IAAI,CAACA,IAAI,CAACE,GAAG,CAACnB,uBAAuB8B;YAClD,OAAO,IAAI,CAACb,IAAI,IAAI,IAAI,CAACA,IAAI,CAACP,IAAI;QACpC;aAUAqB,aAAa,CAACC;YACZ,MAAMC,OAAOC,IAAAA,kBAAU,EAAC;YAExB,6EAA6E;YAC7E,WAAW;YACXD,KAAKE,MAAM,CAAC,IAAI,CAACC,IAAI;YAErB,4EAA4E;YAC5E,2BAA2B;YAC3BH,KAAKE,MAAM,CAACH;YACZ,OAAOC,KAAKI,MAAM,CAAC;QACrB;aAOAC,SAAS,CACPC,SACAC;YAEA,MAAMC,OAAO,AACXD,CAAAA,WAEI,iDAAiD;YACjD,4CAA4C;YAC5C,IAAIE,QAAQ,CAACC,UACXA,QAAQ;oBACNC,aAAa;oBACbC,YAAY;oBACZC,OAAOP;gBACT,MAEF,IAAI,CAACQ,YAAY,CAACR,QAAO,EAE5BS,IAAI,CAAC,CAACF,QAAW,CAAA;oBAChBF,aAAa;oBACbC,YAAY;oBACZC;gBACF,CAAA,GACCG,KAAK,CAAC,CAACC,SAAY,CAAA;oBAClBN,aAAa;oBACbC,YAAY;oBACZK;gBACF,CAAA,EACA,iEAAiE;aAChEF,IAAI,CAAC,CAACG;gBACL,uDAAuD;gBACvD,IAAI,CAACX,UAAU;oBACb,IAAI,CAACY,KAAK,CAACC,MAAM,CAACZ;gBACpB;gBACA,OAAOU;YACT;YAEAV,KAAaF,OAAO,GAAGe,MAAMC,OAAO,CAAChB,WAAWA,UAAU;gBAACA;aAAQ;YACnEE,KAAae,WAAW,GAAG,AAACf,KAAae,WAAW;YACtD,sDAAsD;YACtD,IAAI,CAACJ,KAAK,CAACK,GAAG,CAAChB;YAEf,OAAOA;QACT;aAEAiB,QAAQ;YACN,OAAOhB,QAAQiB,GAAG,CAAC,IAAI,CAACP,KAAK,EAAEH,KAAK,CAAC,IAAM;QAC7C;QAEA,oDAAoD;QACpD,0DAA0D;QAC1D,gCAAgC;aAChCW,gBAAgB,CAAC,EACfC,IAAI,EACJC,GAAG,EACHzD,OAAO,EACP0D,MAAM,EAMP;YACC,wEAAwE;YACxE,MAAMC,YAA8BD,UAAU,EAAE;YAEhD,IAAIA,WAAW,MAAM;gBACnB,IAAI,CAACX,KAAK,CAACa,OAAO,CAAC,CAACC;oBAClB,IAAI;4BACFA;yBAAAA,oBAAAA,KAAKV,WAAW,qBAAhBU,kBAAkBC,KAAK;wBACvBH,UAAUI,IAAI,IAAIF,KAAK3B,OAAO;oBAChC,EAAE,OAAO8B,GAAG;oBACV,wCAAwC;oBAC1C;gBACF;YACF;YAEA,IAAIL,UAAUM,MAAM,KAAK,GAAG;gBAC1B,qBAAqB;gBACrB;YACF;YAEA,qFAAqF;YACrF,MAAMC,kBAAkB7D,aAAI,CAACC,IAAI,CAAC,IAAI,CAACN,OAAO,EAAE;YAChDmE,WAAE,CAACC,SAAS,CAACF,iBAAiB;gBAAEG,WAAW;YAAK;YAChD,mFAAmF;YACnF,MAAMC,aAAa,CAAC,QAAQ,EAAEC,QAAQC,GAAG,CAAC,CAAC,EAAEC,IAAAA,mBAAW,EAAC,GAAGxD,QAAQ,CAAC,OAAO,KAAK,CAAC;YAClFkD,WAAE,CAACO,aAAa,CACdrE,aAAI,CAACC,IAAI,CAAC4D,iBAAiBI,aAC3BK,KAAKC,SAAS,CAACjB;YAGjB,kDAAkD;YAClD,0DAA0D;YAC1D,MAAMkB,gBACJC,QAAQ;YAEV,2DAA2D;YAC3D,6BAA6B;YAC7B,MAAMC,QAAQ,IAAI,CAACC,oBAAoB,GACnCH,cAAcI,SAAS,GACvBJ,cAAcE,KAAK;YAEvBA,MACER,QAAQW,QAAQ,EAChB;gBACEJ,QAAQxC,OAAO,CAAC;gBAChBkB;gBACAC;gBACAa;mBACItE,UAAU;oBAACA;iBAAQ,GAAG,EAAE;aAC7B,EACD;gBACEmF,UAAU,CAAC,IAAI,CAACH,oBAAoB;gBACpCI,aAAa;gBACbC,OAAO;gBACP,GAAI,IAAI,CAACL,oBAAoB,GACzB;oBACEM,OAAO;gBACT,IACA,CAAC,CAAC;YACR;QAEJ;aAEQ5C,eAAe,OACrBR;YAEA,IAAIwB;YACJ,IAAIT,MAAMC,OAAO,CAAChB,UAAU;gBAC1BwB,SAASxB;YACX,OAAO;gBACLwB,SAAS;oBAACxB;iBAAQ;YACpB;YAEA,IAAIwB,OAAOO,MAAM,GAAG,GAAG;gBACrB,OAAO5B,QAAQC,OAAO;YACxB;YAEA,IAAI,IAAI,CAAC0C,oBAAoB,EAAE;gBAC7B,0EAA0E;gBAC1E,yDAAyD;gBACzD,MAAMO,OAAO,MAAMC,IAAAA,+BAAgB;gBACnC,oEAAoE;gBACpE,oEAAoE;gBACpE,OAAO,IAAInD,QAAQ,CAACC;oBAClBmD,WAAW;wBACT,2DAA2D;wBAC3D/B,OAAOE,OAAO,CAAC,CAAC,EAAE8B,SAAS,EAAE/D,OAAO,EAAE,GACpCT,QAAQyE,KAAK,CACX,CAAC,YAAY,CAAC,GACZhB,KAAKC,SAAS,CAAC;gCAAEc;gCAAW/D;gCAAS4D;4BAAK,GAAG,MAAM;wBAGzDjD,QAAQ/B;oBACV,GAAG;gBACL;YACF;YAEA,sDAAsD;YACtD,IAAI,IAAI,CAACI,UAAU,EAAE;gBACnB,OAAO0B,QAAQC,OAAO;YACxB;YAEA,MAAMsD,iBAAiB,IAAIC,yBAAe;YAC1C,MAAM/C,MAAMgD,IAAAA,8CAAwB,EAClC;gBACEC,SAAS;oBACPC,aAAa,IAAI,CAACA,WAAW;oBAC7BC,WAAW,MAAM,IAAI,CAACC,YAAY;oBAClCC,WAAW,IAAI,CAACA,SAAS;gBAC3B;gBACAZ,MAAM,MAAMC,IAAAA,+BAAgB;gBAC5B9B,QAAQA,OAAO0C,GAAG,CAAC,CAAC,EAAEV,SAAS,EAAE/D,OAAO,EAAE,GAAM,CAAA;wBAC9C+D;wBACAW,QAAQ1E;oBACV,CAAA;YACF,GACAiE,eAAeU,MAAM;YAEvB,oFAAoF;YACpF,MAAMC,UAAUd,WAAW,IAAMG,eAAe9B,KAAK,IAAI;YACzDhB,IAAIK,WAAW,GAAGyC;YAClB,OAAO9C,IAAI0D,OAAO,CAAC,IAAMC,aAAaF;QACxC;QAzSE,oEAAoE;QACpE,MAAM,EAAEG,uBAAuB,EAAE1B,oBAAoB,EAAE,GAAGT,QAAQoC,GAAG;QACrE,IAAI,CAACD,uBAAuB,GAAGA;QAC/B,IAAI,CAAC1B,oBAAoB,GAAGA;QAC5B,IAAI,CAAChF,OAAO,GAAGA;QACf,MAAM4G,mBAAmB7G,oBAAoBC;QAE7C,IAAI;YACF,qEAAqE;YACrE,wEAAwE;YACxE,qBAAqB;YACrB,IAAI,CAACY,IAAI,GAAG,IAAIiG,aAAI,CAAC;gBAAEC,aAAa;gBAAUC,KAAKH;YAAiB;QACtE,EAAE,OAAO5C,GAAG;YACV,IAAI,CAACpD,IAAI,GAAG;QACd;QACA,IAAI,CAACuF,SAAS,GAAG1B,IAAAA,mBAAW,EAAC,IAAIxD,QAAQ,CAAC;QAC1C,IAAI,CAAC8B,KAAK,GAAG,IAAIiE;QAEjB,IAAI,CAACvG,YAAY;YACf,IAAI,CAACC,MAAM;QACb;IACF;IA+BA,IAAIsF,cAAsB;QACxB,MAAMiB,MAAM,IAAI,CAACrG,IAAI,IAAI,IAAI,CAACA,IAAI,CAACC,GAAG,CAAChB;QACvC,IAAIoH,KAAK;YACP,OAAOA;QACT;QAEA,MAAMC,YAAYzC,IAAAA,mBAAW,EAAC,IAAIxD,QAAQ,CAAC;QAC3C,IAAI,CAACL,IAAI,IAAI,IAAI,CAACA,IAAI,CAACE,GAAG,CAACjB,kBAAkBqH;QAC7C,OAAOA;IACT;IAEA,IAAInF,OAAe;QACjB,MAAMkF,MAAM,IAAI,CAACrG,IAAI,IAAI,IAAI,CAACA,IAAI,CAACC,GAAG,CAACf;QACvC,IAAImH,KAAK;YACP,OAAOA;QACT;QAEA,MAAMC,YAAYzC,IAAAA,mBAAW,EAAC,IAAIxD,QAAQ,CAAC;QAC3C,IAAI,CAACL,IAAI,IAAI,IAAI,CAACA,IAAI,CAACE,GAAG,CAAChB,oBAAoBoH;QAC/C,OAAOA;IACT;IAEA,IAAYvG,aAAsB;QAChC,IAAI,CAAC,CAAC,IAAI,CAAC+F,uBAAuB,IAAI,CAAC,IAAI,CAAC9F,IAAI,EAAE;YAChD,OAAO;QACT;QACA,OAAO,IAAI,CAACA,IAAI,CAACC,GAAG,CAAClB,uBAAuB,UAAU;IACxD;IAQA,IAAIwH,YAAqB;QACvB,OACE,CAAC,IAAI,CAACT,uBAAuB,IAC7B,CAAC,CAAC,IAAI,CAAC9F,IAAI,IACX,IAAI,CAACA,IAAI,CAACC,GAAG,CAAClB,uBAAuB,UAAU;IAEnD;IAeA,MAAcuG,eAAgC;QAC5C,IAAI,CAACkB,aAAa,GAAG,IAAI,CAACA,aAAa,IAAIC,IAAAA,0BAAe;QAC1D,OAAO,IAAI,CAAC3F,UAAU,CAAC,MAAM,IAAI,CAAC0F,aAAa;IACjD;AA2LF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/index.d.ts b/e-commerce/node_modules/next/dist/trace/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efe023e2ef75d406b5da87c9ce610734c45abde3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/index.d.ts @@ -0,0 +1,5 @@ +import { trace, exportTraceState, flushAllTraces, getTraceEvents, initializeTraceState, recordTraceEvents, Span, SpanStatus, hrtimeToEpochNanoseconds } from './trace'; +import { setGlobal } from './shared'; +import type { SpanId, TraceEvent, TraceState } from './types'; +export { trace, exportTraceState, flushAllTraces, getTraceEvents, hrtimeToEpochNanoseconds, initializeTraceState, recordTraceEvents, Span, setGlobal, SpanStatus, }; +export type { SpanId, TraceEvent, TraceState }; diff --git a/e-commerce/node_modules/next/dist/trace/index.js b/e-commerce/node_modules/next/dist/trace/index.js new file mode 100644 index 0000000000000000000000000000000000000000..09c3f597a95d7f5add4fad4042b8e5885c13ddc7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/index.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + Span: null, + SpanStatus: null, + exportTraceState: null, + flushAllTraces: null, + getTraceEvents: null, + hrtimeToEpochNanoseconds: null, + initializeTraceState: null, + recordTraceEvents: null, + setGlobal: null, + trace: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + Span: function() { + return _trace.Span; + }, + SpanStatus: function() { + return _trace.SpanStatus; + }, + exportTraceState: function() { + return _trace.exportTraceState; + }, + flushAllTraces: function() { + return _trace.flushAllTraces; + }, + getTraceEvents: function() { + return _trace.getTraceEvents; + }, + hrtimeToEpochNanoseconds: function() { + return _trace.hrtimeToEpochNanoseconds; + }, + initializeTraceState: function() { + return _trace.initializeTraceState; + }, + recordTraceEvents: function() { + return _trace.recordTraceEvents; + }, + setGlobal: function() { + return _shared.setGlobal; + }, + trace: function() { + return _trace.trace; + } +}); +const _trace = require("./trace"); +const _shared = require("./shared"); + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/index.js.map b/e-commerce/node_modules/next/dist/trace/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5251f8c1e091736b32c2679533379cffc482a4f6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/trace/index.ts"],"sourcesContent":["import {\n trace,\n exportTraceState,\n flushAllTraces,\n getTraceEvents,\n initializeTraceState,\n recordTraceEvents,\n Span,\n SpanStatus,\n hrtimeToEpochNanoseconds,\n} from './trace'\nimport { setGlobal } from './shared'\nimport type { SpanId, TraceEvent, TraceState } from './types'\n\nexport {\n trace,\n exportTraceState,\n flushAllTraces,\n getTraceEvents,\n hrtimeToEpochNanoseconds,\n initializeTraceState,\n recordTraceEvents,\n Span,\n setGlobal,\n SpanStatus,\n}\nexport type { SpanId, TraceEvent, TraceState }\n"],"names":["Span","SpanStatus","exportTraceState","flushAllTraces","getTraceEvents","hrtimeToEpochNanoseconds","initializeTraceState","recordTraceEvents","setGlobal","trace"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IAsBEA,IAAI;eAAJA,WAAI;;IAEJC,UAAU;eAAVA,iBAAU;;IARVC,gBAAgB;eAAhBA,uBAAgB;;IAChBC,cAAc;eAAdA,qBAAc;;IACdC,cAAc;eAAdA,qBAAc;;IACdC,wBAAwB;eAAxBA,+BAAwB;;IACxBC,oBAAoB;eAApBA,2BAAoB;;IACpBC,iBAAiB;eAAjBA,wBAAiB;;IAEjBC,SAAS;eAATA,iBAAS;;IARTC,KAAK;eAALA,YAAK;;;uBALA;wBACmB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/index.d.ts b/e-commerce/node_modules/next/dist/trace/report/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfd0db5161a2c729fdbd54021256f0435d3d6091 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/index.d.ts @@ -0,0 +1,11 @@ +import type { TraceEvent } from '../types'; +import type { Reporter } from './types'; +declare class MultiReporter implements Reporter { + private reporters; + constructor(reporters: Reporter[]); + flushAll(): void; + close(): void; + report(event: TraceEvent): void; +} +export declare const reporter: MultiReporter; +export {}; diff --git a/e-commerce/node_modules/next/dist/trace/report/index.js b/e-commerce/node_modules/next/dist/trace/report/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f66aeffd9fa9127199042c238788ffa30d915ee4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/index.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "reporter", { + enumerable: true, + get: function() { + return reporter; + } +}); +const _totelemetry = /*#__PURE__*/ _interop_require_default(require("./to-telemetry")); +const _tojson = /*#__PURE__*/ _interop_require_default(require("./to-json")); +const _tojsonbuild = /*#__PURE__*/ _interop_require_default(require("./to-json-build")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +class MultiReporter { + constructor(reporters){ + this.reporters = []; + this.reporters = reporters; + } + flushAll() { + this.reporters.forEach((reporter)=>reporter.flushAll()); + } + close() { + this.reporters.forEach((reporter)=>reporter.close == null ? void 0 : reporter.close.call(reporter)); + } + report(event) { + this.reporters.forEach((reporter)=>reporter.report(event)); + } +} +const reporter = new MultiReporter([ + _tojson.default, + _tojsonbuild.default, + _totelemetry.default +]); + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/index.js.map b/e-commerce/node_modules/next/dist/trace/report/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..540c03690573006c24d295a13d96fa98f35f916e --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/trace/report/index.ts"],"sourcesContent":["import type { TraceEvent } from '../types'\nimport reportToTelemetry from './to-telemetry'\nimport reportToJson from './to-json'\nimport reportToJsonBuild from './to-json-build'\nimport type { Reporter } from './types'\n\nclass MultiReporter implements Reporter {\n private reporters: Reporter[] = []\n\n constructor(reporters: Reporter[]) {\n this.reporters = reporters\n }\n\n flushAll() {\n this.reporters.forEach((reporter) => reporter.flushAll())\n }\n\n close() {\n this.reporters.forEach((reporter) => reporter.close?.())\n }\n\n report(event: TraceEvent) {\n this.reporters.forEach((reporter) => reporter.report(event))\n }\n}\n\n// JSON is always reported to allow for diagnostics\nexport const reporter = new MultiReporter([\n reportToJson,\n reportToJsonBuild,\n reportToTelemetry,\n])\n"],"names":["reporter","MultiReporter","constructor","reporters","flushAll","forEach","close","report","event","reportToJson","reportToJsonBuild","reportToTelemetry"],"mappings":";;;;+BA2BaA;;;eAAAA;;;oEA1BiB;+DACL;oEACK;;;;;;AAG9B,MAAMC;IAGJC,YAAYC,SAAqB,CAAE;aAF3BA,YAAwB,EAAE;QAGhC,IAAI,CAACA,SAAS,GAAGA;IACnB;IAEAC,WAAW;QACT,IAAI,CAACD,SAAS,CAACE,OAAO,CAAC,CAACL,WAAaA,SAASI,QAAQ;IACxD;IAEAE,QAAQ;QACN,IAAI,CAACH,SAAS,CAACE,OAAO,CAAC,CAACL,WAAaA,SAASM,KAAK,oBAAdN,SAASM,KAAK,MAAdN;IACvC;IAEAO,OAAOC,KAAiB,EAAE;QACxB,IAAI,CAACL,SAAS,CAACE,OAAO,CAAC,CAACL,WAAaA,SAASO,MAAM,CAACC;IACvD;AACF;AAGO,MAAMR,WAAW,IAAIC,cAAc;IACxCQ,eAAY;IACZC,oBAAiB;IACjBC,oBAAiB;CAClB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/index.test.js b/e-commerce/node_modules/next/dist/trace/report/index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f6f1913e7b745e2ea1f70b0ad0ec88d6b155106b --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/index.test.js @@ -0,0 +1,74 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _promises = require("fs/promises"); +const _ = require("."); +const _shared = require("../shared"); +const _path = require("path"); +const _os = require("os"); +const TRACE_EVENT = { + name: 'test-span', + duration: 321, + timestamp: Date.now(), + id: 127, + startTime: Date.now() +}; +const WEBPACK_INVALIDATED_EVENT = { + name: 'webpack-invalidated', + duration: 100, + timestamp: Date.now(), + id: 112, + startTime: Date.now() +}; +describe('Trace Reporter', ()=>{ + const tmpDirs = []; + afterAll(async ()=>{ + // Windows refuses to remove a directory containing an open file, so the + // trace file handle has to go first. + _.reporter.close(); + await Promise.all(tmpDirs.splice(0).map((dir)=>(0, _promises.rm)(dir, { + recursive: true, + force: true + }))); + }); + describe('JSON reporter', ()=>{ + it('should write the trace events to JSON file', async ()=>{ + const tmpDir = await (0, _promises.mkdtemp)((0, _path.join)((0, _os.tmpdir)(), 'json-reporter')); + tmpDirs.push(tmpDir); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', 'anything'); + _.reporter.report(TRACE_EVENT); + _.reporter.flushAll(); + const traceFilename = (0, _path.join)(tmpDir, 'trace'); + const traces = JSON.parse(await (0, _promises.readFile)(traceFilename, 'utf-8')); + expect(traces.length).toEqual(1); + expect(traces[0].name).toEqual('test-span'); + expect(traces[0].id).toEqual(127); + expect(traces[0].duration).toEqual(321); + expect(traces[0].traceId).toBeDefined(); + }); + }); + describe('Telemetry reporter', ()=>{ + it('should record telemetry event', async ()=>{ + const recordMock = jest.fn(); + const telemetryMock = { + record: recordMock + }; + (0, _shared.setGlobal)('telemetry', telemetryMock); + // This should be ignored. + _.reporter.report(TRACE_EVENT); + expect(recordMock).toHaveBeenCalledTimes(0); + _.reporter.report(WEBPACK_INVALIDATED_EVENT); + expect(recordMock).toHaveBeenCalledTimes(1); + expect(recordMock).toHaveBeenCalledWith({ + eventName: 'WEBPACK_INVALIDATED', + payload: { + durationInMicroseconds: 100 + } + }); + }); + }); +}); + +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/index.test.js.map b/e-commerce/node_modules/next/dist/trace/report/index.test.js.map new file mode 100644 index 0000000000000000000000000000000000000000..26f6877ce1a1dedaaefeaf295d611193206e67e0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/trace/report/index.test.ts"],"sourcesContent":["import { mkdtemp, readFile, rm } from 'fs/promises'\nimport { reporter } from '.'\nimport { setGlobal } from '../shared'\nimport { join } from 'path'\nimport { tmpdir } from 'os'\n\nconst TRACE_EVENT = {\n name: 'test-span',\n duration: 321,\n timestamp: Date.now(),\n id: 127,\n startTime: Date.now(),\n}\nconst WEBPACK_INVALIDATED_EVENT = {\n name: 'webpack-invalidated',\n duration: 100,\n timestamp: Date.now(),\n id: 112,\n startTime: Date.now(),\n}\n\ndescribe('Trace Reporter', () => {\n const tmpDirs: string[] = []\n\n afterAll(async () => {\n // Windows refuses to remove a directory containing an open file, so the\n // trace file handle has to go first.\n reporter.close()\n await Promise.all(\n tmpDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))\n )\n })\n\n describe('JSON reporter', () => {\n it('should write the trace events to JSON file', async () => {\n const tmpDir = await mkdtemp(join(tmpdir(), 'json-reporter'))\n tmpDirs.push(tmpDir)\n setGlobal('distDir', tmpDir)\n setGlobal('phase', 'anything')\n reporter.report(TRACE_EVENT)\n reporter.flushAll()\n const traceFilename = join(tmpDir, 'trace')\n const traces = JSON.parse(await readFile(traceFilename, 'utf-8'))\n expect(traces.length).toEqual(1)\n expect(traces[0].name).toEqual('test-span')\n expect(traces[0].id).toEqual(127)\n expect(traces[0].duration).toEqual(321)\n expect(traces[0].traceId).toBeDefined()\n })\n })\n\n describe('Telemetry reporter', () => {\n it('should record telemetry event', async () => {\n const recordMock = jest.fn()\n const telemetryMock = {\n record: recordMock,\n }\n setGlobal('telemetry', telemetryMock)\n // This should be ignored.\n reporter.report(TRACE_EVENT)\n expect(recordMock).toHaveBeenCalledTimes(0)\n reporter.report(WEBPACK_INVALIDATED_EVENT)\n expect(recordMock).toHaveBeenCalledTimes(1)\n expect(recordMock).toHaveBeenCalledWith({\n eventName: 'WEBPACK_INVALIDATED',\n payload: {\n durationInMicroseconds: 100,\n },\n })\n })\n })\n})\n"],"names":["TRACE_EVENT","name","duration","timestamp","Date","now","id","startTime","WEBPACK_INVALIDATED_EVENT","describe","tmpDirs","afterAll","reporter","close","Promise","all","splice","map","dir","rm","recursive","force","it","tmpDir","mkdtemp","join","tmpdir","push","setGlobal","report","flushAll","traceFilename","traces","JSON","parse","readFile","expect","length","toEqual","traceId","toBeDefined","recordMock","jest","fn","telemetryMock","record","toHaveBeenCalledTimes","toHaveBeenCalledWith","eventName","payload","durationInMicroseconds"],"mappings":";;;;0BAAsC;kBACb;wBACC;sBACL;oBACE;AAEvB,MAAMA,cAAc;IAClBC,MAAM;IACNC,UAAU;IACVC,WAAWC,KAAKC,GAAG;IACnBC,IAAI;IACJC,WAAWH,KAAKC,GAAG;AACrB;AACA,MAAMG,4BAA4B;IAChCP,MAAM;IACNC,UAAU;IACVC,WAAWC,KAAKC,GAAG;IACnBC,IAAI;IACJC,WAAWH,KAAKC,GAAG;AACrB;AAEAI,SAAS,kBAAkB;IACzB,MAAMC,UAAoB,EAAE;IAE5BC,SAAS;QACP,wEAAwE;QACxE,qCAAqC;QACrCC,UAAQ,CAACC,KAAK;QACd,MAAMC,QAAQC,GAAG,CACfL,QAAQM,MAAM,CAAC,GAAGC,GAAG,CAAC,CAACC,MAAQC,IAAAA,YAAE,EAACD,KAAK;gBAAEE,WAAW;gBAAMC,OAAO;YAAK;IAE1E;IAEAZ,SAAS,iBAAiB;QACxBa,GAAG,8CAA8C;YAC/C,MAAMC,SAAS,MAAMC,IAAAA,iBAAO,EAACC,IAAAA,UAAI,EAACC,IAAAA,UAAM,KAAI;YAC5ChB,QAAQiB,IAAI,CAACJ;YACbK,IAAAA,iBAAS,EAAC,WAAWL;YACrBK,IAAAA,iBAAS,EAAC,SAAS;YACnBhB,UAAQ,CAACiB,MAAM,CAAC7B;YAChBY,UAAQ,CAACkB,QAAQ;YACjB,MAAMC,gBAAgBN,IAAAA,UAAI,EAACF,QAAQ;YACnC,MAAMS,SAASC,KAAKC,KAAK,CAAC,MAAMC,IAAAA,kBAAQ,EAACJ,eAAe;YACxDK,OAAOJ,OAAOK,MAAM,EAAEC,OAAO,CAAC;YAC9BF,OAAOJ,MAAM,CAAC,EAAE,CAAC/B,IAAI,EAAEqC,OAAO,CAAC;YAC/BF,OAAOJ,MAAM,CAAC,EAAE,CAAC1B,EAAE,EAAEgC,OAAO,CAAC;YAC7BF,OAAOJ,MAAM,CAAC,EAAE,CAAC9B,QAAQ,EAAEoC,OAAO,CAAC;YACnCF,OAAOJ,MAAM,CAAC,EAAE,CAACO,OAAO,EAAEC,WAAW;QACvC;IACF;IAEA/B,SAAS,sBAAsB;QAC7Ba,GAAG,iCAAiC;YAClC,MAAMmB,aAAaC,KAAKC,EAAE;YAC1B,MAAMC,gBAAgB;gBACpBC,QAAQJ;YACV;YACAb,IAAAA,iBAAS,EAAC,aAAagB;YACvB,0BAA0B;YAC1BhC,UAAQ,CAACiB,MAAM,CAAC7B;YAChBoC,OAAOK,YAAYK,qBAAqB,CAAC;YACzClC,UAAQ,CAACiB,MAAM,CAACrB;YAChB4B,OAAOK,YAAYK,qBAAqB,CAAC;YACzCV,OAAOK,YAAYM,oBAAoB,CAAC;gBACtCC,WAAW;gBACXC,SAAS;oBACPC,wBAAwB;gBAC1B;YACF;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/to-json-build.d.ts b/e-commerce/node_modules/next/dist/trace/report/to-json-build.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb80f32bede66b1f9852464232d0bc15327a7f8a --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-json-build.d.ts @@ -0,0 +1,2 @@ +declare const _default: import("./types").Reporter; +export default _default; diff --git a/e-commerce/node_modules/next/dist/trace/report/to-json-build.js b/e-commerce/node_modules/next/dist/trace/report/to-json-build.js new file mode 100644 index 0000000000000000000000000000000000000000..490e70714fdca4cbec35248ff994b9811058f4f8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-json-build.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _shared = require("../shared"); +const _constants = require("../../shared/lib/constants"); +const _tojson = require("./to-json"); +const allowlistedEvents = new Set([ + 'next-build', + 'run-turbopack', + 'run-webpack', + 'run-typescript', + 'run-eslint', + 'static-check', + 'collect-build-traces', + 'static-generation', + 'output-export-full-static-export', + 'adapter-handle-build-complete', + 'output-standalone', + 'telemetry-flush', + 'turbopack-persistence', + 'turbopack-compaction', + 'turbopack-module-graph', + 'turbopack-write-entrypoints', + 'turbopack-emit' +]); +const _default = (0, _tojson.createJsonReporter)({ + filename: 'trace-build', + sizeLimit: Infinity, + filter: (event)=>{ + const phase = _shared.traceGlobals.get('phase'); + return phase === _constants.PHASE_PRODUCTION_BUILD && allowlistedEvents.has(event.name); + } +}); + +//# sourceMappingURL=to-json-build.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/to-json-build.js.map b/e-commerce/node_modules/next/dist/trace/report/to-json-build.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4666347f5efc7703c91afbf6030dea328cab092b --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-json-build.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/trace/report/to-json-build.ts"],"sourcesContent":["import { traceGlobals } from '../shared'\nimport { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants'\nimport { createJsonReporter } from './to-json'\n\nconst allowlistedEvents = new Set([\n 'next-build',\n 'run-turbopack',\n 'run-webpack',\n 'run-typescript',\n 'run-eslint',\n 'static-check',\n 'collect-build-traces',\n 'static-generation',\n 'output-export-full-static-export',\n 'adapter-handle-build-complete',\n 'output-standalone',\n 'telemetry-flush',\n 'turbopack-persistence',\n 'turbopack-compaction',\n 'turbopack-module-graph',\n 'turbopack-write-entrypoints',\n 'turbopack-emit',\n])\n\nexport default createJsonReporter({\n filename: 'trace-build',\n sizeLimit: Infinity,\n filter: (event) => {\n const phase = traceGlobals.get('phase')\n return phase === PHASE_PRODUCTION_BUILD && allowlistedEvents.has(event.name)\n },\n})\n"],"names":["allowlistedEvents","Set","createJsonReporter","filename","sizeLimit","Infinity","filter","event","phase","traceGlobals","get","PHASE_PRODUCTION_BUILD","has","name"],"mappings":";;;;+BAwBA;;;eAAA;;;wBAxB6B;2BACU;wBACJ;AAEnC,MAAMA,oBAAoB,IAAIC,IAAI;IAChC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;MAED,WAAeC,IAAAA,0BAAkB,EAAC;IAChCC,UAAU;IACVC,WAAWC;IACXC,QAAQ,CAACC;QACP,MAAMC,QAAQC,oBAAY,CAACC,GAAG,CAAC;QAC/B,OAAOF,UAAUG,iCAAsB,IAAIX,kBAAkBY,GAAG,CAACL,MAAMM,IAAI;IAC7E;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/to-json.d.ts b/e-commerce/node_modules/next/dist/trace/report/to-json.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f41caacde1bb9a48b45e0a36be9a9e101ef464d5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-json.d.ts @@ -0,0 +1,9 @@ +import type { TraceEvent } from '../types'; +import type { Reporter } from './types'; +export declare function createJsonReporter(options: { + filename: string; + sizeLimit: number | ((phase: string) => number); + filter?: (event: TraceEvent) => boolean; +}): Reporter; +declare const _default: Reporter; +export default _default; diff --git a/e-commerce/node_modules/next/dist/trace/report/to-json.js b/e-commerce/node_modules/next/dist/trace/report/to-json.js new file mode 100644 index 0000000000000000000000000000000000000000..323462647942e5f049d3285790b08578ab9523ea --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-json.js @@ -0,0 +1,215 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createJsonReporter: null, + default: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createJsonReporter: function() { + return createJsonReporter; + }, + default: function() { + return _default; + } +}); +const _shared = require("../shared"); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _constants = require("../../shared/lib/constants"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +// The webpack/rspack profiling plugins open a span per module, so writing +// events individually would put a syscall in the middle of every module build. +const BUFFER_SIZE = 16 * 1024; +// Each flush is wrapped as a JSON array; the tail of the buffer is reserved +// for this and never used by event data. +const TERMINATOR = Buffer.from(']\n', 'utf8'); +const MAX_UTF8_CHAR_BYTES = 4; +/** + * An append-only newline-delimited JSON file. + * + * Closing is not part of the normal lifetime: `writeSync` hands the bytes to + * the OS before it returns, so once flushed they survive `process.exit()` and + * crashes that run no shutdown path. Only the unflushed tail is at risk, which + * is why `flush()` is called wherever traces need to be on disk. `close()` + * exists for callers that must then act on the file itself. + */ class RotatingWriteStream { + constructor(file, sizeLimit){ + this.buffer = Buffer.allocUnsafe(BUFFER_SIZE); + // Bytes of event data in `buffer`, excluding the terminator written at + // flush time. 0 means nothing is pending. + this.buffered = 0; + this.size = 0; + this.file = file; + this.sizeLimit = sizeLimit; + // TODO: opening a file in append mode like we do in dev should seed the + // size from the current file size. + this.size = 0; + } + /** + * Open on first write rather than up front. The dev server records spans + * before it cleans its dist dir, and a descriptor opened that early would be + * unlinked by the clean -- writes to the orphaned inode still succeed, so + * the trace would silently never appear on disk. + */ open() { + if (this.fd === undefined) { + _fs.default.mkdirSync(_path.default.dirname(this.file), { + recursive: true + }); + // In dev, append so traces accumulate across sessions. In production, + // truncate so each build starts with a fresh trace file. + this.fd = _fs.default.openSync(this.file, _shared.traceGlobals.get('phase') === _constants.PHASE_DEVELOPMENT_SERVER ? 'a' : 'w'); + } + return this.fd; + } + // Recreate the file + rotate() { + this.closeFd(); + _fs.default.mkdirSync(_path.default.dirname(this.file), { + recursive: true + }); + // Opening in 'w' mode truncates the file, discarding what rotated out. + this.fd = _fs.default.openSync(this.file, 'w'); + this.size = 0; + } + /** + * Append one already-encoded event. Events are written as a single JSON + * array per flush, which is the format readers expect (see + * `parseTraceEvents` and the trace uploader). + */ write(encodedEvent) { + const capacity = this.buffer.length - TERMINATOR.length; + if (this.tryWriteToBuffer(encodedEvent, capacity)) { + return; + } + // Didn't fit. Start a fresh batch and try again. + this.flush(); + if (this.tryWriteToBuffer(encodedEvent, capacity)) { + return; + } + // Too large to ever fit in the buffer, so give it a batch of its own. + this.writeToFile(Buffer.from(`[${encodedEvent}]\n`, 'utf8')); + } + /** + * Append `[event` or `,event` to the buffer, returning false without + * modifying it if the whole thing does not fit. + */ tryWriteToBuffer(encodedEvent, capacity) { + // `[` opens a new batch, `,` separates events within one. + const prefix = this.buffered === 0 ? '[' : ','; + const written = this.buffer.write(prefix + encodedEvent, this.buffered, capacity - this.buffered, 'utf8'); + // `Buffer.write` truncates silently, so the byte count is the only signal + // that the event did not fit -- and because it stops at the last whole + // character, a truncated write can still leave a few bytes unused. Only a + // write that ends clear of that margin is known to be complete. + if (this.buffered + written > capacity - MAX_UTF8_CHAR_BYTES) { + return false; + } + this.buffered += written; + return true; + } + flush() { + if (this.buffered === 0) { + return; + } + this.buffered += TERMINATOR.copy(this.buffer, this.buffered); + const data = this.buffer.subarray(0, this.buffered); + this.buffered = 0; + this.writeToFile(data); + } + writeToFile(data) { + let offset = 0; + try { + if (this.size + data.length > this.sizeLimit) { + this.rotate(); + } + const fd = this.open(); + // writeSync can write fewer than all the bytes + while(offset < data.length){ + offset += _fs.default.writeSync(fd, data, offset); + } + } catch (err) { + // Tracing is diagnostic, so a failed write should not fail the build. + // N.B. This is incredibly rare and a torn write means the data may be corrupted on disk. + console.log(err); + } + this.size += offset; + } + /** + * Release the descriptor without flushing. Callers that want the buffered + * tail on disk flush first; `rotate` deliberately does not. + */ closeFd() { + if (this.fd === undefined) { + return; + } + try { + _fs.default.closeSync(this.fd); + } catch { + // Nothing useful to do if the descriptor is already gone. + } + this.fd = undefined; + } + /** + * Flush and release the descriptor. Only needed when something else has to + * act on the file (Windows cannot remove a file that is still open), which + * in practice means tests -- the normal lifetime of the process is the + * lifetime of the trace. + */ close() { + this.flush(); + this.closeFd(); + } +} +function createJsonReporter(options) { + let writeStream; + function report(event) { + if (options.filter && !options.filter(event)) { + return; + } + const distDir = _shared.traceGlobals.get('distDir'); + const phase = _shared.traceGlobals.get('phase'); + if (!distDir || !phase) { + return; + } + const file = _path.default.join(distDir, options.filename); + // `distDir` can change within a process (most visibly between tests), so + // a stream opened against a previous one must not keep receiving events. + if (writeStream && writeStream.file !== file) { + writeStream.close(); + writeStream = undefined; + } + if (!writeStream) { + // Constructing the stream touches no filesystem state -- the directory + // and file are created lazily on the first write. + const limit = typeof options.sizeLimit === 'function' ? options.sizeLimit(phase) : options.sizeLimit; + writeStream = new RotatingWriteStream(file, limit); + } + writeStream.write(JSON.stringify({ + ...event, + traceId: _shared.traceId + })); + } + return { + flushAll: ()=>writeStream == null ? void 0 : writeStream.flush(), + close: ()=>{ + writeStream == null ? void 0 : writeStream.close(); + writeStream = undefined; + }, + report + }; +} +const _default = createJsonReporter({ + filename: 'trace', + sizeLimit: (phase)=>// Development is limited to 50MB, production is unlimited + phase === _constants.PHASE_DEVELOPMENT_SERVER ? 52428800 : Infinity +}); + +//# sourceMappingURL=to-json.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/to-json.js.map b/e-commerce/node_modules/next/dist/trace/report/to-json.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bbc6b5abd7f2f700f7a20b69b4a6adf8581c0a83 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-json.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/trace/report/to-json.ts"],"sourcesContent":["import { traceGlobals, traceId } from '../shared'\nimport fs from 'fs'\nimport path from 'path'\nimport { PHASE_DEVELOPMENT_SERVER } from '../../shared/lib/constants'\nimport type { TraceEvent } from '../types'\nimport type { Reporter } from './types'\n\n// The webpack/rspack profiling plugins open a span per module, so writing\n// events individually would put a syscall in the middle of every module build.\nconst BUFFER_SIZE = 16 * 1024\n// Each flush is wrapped as a JSON array; the tail of the buffer is reserved\n// for this and never used by event data.\nconst TERMINATOR = Buffer.from(']\\n', 'utf8')\nconst MAX_UTF8_CHAR_BYTES = 4\n\n/**\n * An append-only newline-delimited JSON file.\n *\n * Closing is not part of the normal lifetime: `writeSync` hands the bytes to\n * the OS before it returns, so once flushed they survive `process.exit()` and\n * crashes that run no shutdown path. Only the unflushed tail is at risk, which\n * is why `flush()` is called wherever traces need to be on disk. `close()`\n * exists for callers that must then act on the file itself.\n */\nclass RotatingWriteStream {\n readonly file: string\n // Undefined until the first write; see `open()`.\n private fd: number | undefined\n private readonly buffer = Buffer.allocUnsafe(BUFFER_SIZE)\n // Bytes of event data in `buffer`, excluding the terminator written at\n // flush time. 0 means nothing is pending.\n private buffered: number = 0\n private size: number = 0\n private readonly sizeLimit: number\n\n constructor(file: string, sizeLimit: number) {\n this.file = file\n this.sizeLimit = sizeLimit\n // TODO: opening a file in append mode like we do in dev should seed the\n // size from the current file size.\n this.size = 0\n }\n\n /**\n * Open on first write rather than up front. The dev server records spans\n * before it cleans its dist dir, and a descriptor opened that early would be\n * unlinked by the clean -- writes to the orphaned inode still succeed, so\n * the trace would silently never appear on disk.\n */\n private open(): number {\n if (this.fd === undefined) {\n fs.mkdirSync(path.dirname(this.file), { recursive: true })\n // In dev, append so traces accumulate across sessions. In production,\n // truncate so each build starts with a fresh trace file.\n this.fd = fs.openSync(\n this.file,\n traceGlobals.get('phase') === PHASE_DEVELOPMENT_SERVER ? 'a' : 'w'\n )\n }\n return this.fd\n }\n\n // Recreate the file\n private rotate() {\n this.closeFd()\n fs.mkdirSync(path.dirname(this.file), { recursive: true })\n // Opening in 'w' mode truncates the file, discarding what rotated out.\n this.fd = fs.openSync(this.file, 'w')\n this.size = 0\n }\n\n /**\n * Append one already-encoded event. Events are written as a single JSON\n * array per flush, which is the format readers expect (see\n * `parseTraceEvents` and the trace uploader).\n */\n write(encodedEvent: string): void {\n const capacity = this.buffer.length - TERMINATOR.length\n if (this.tryWriteToBuffer(encodedEvent, capacity)) {\n return\n }\n\n // Didn't fit. Start a fresh batch and try again.\n this.flush()\n if (this.tryWriteToBuffer(encodedEvent, capacity)) {\n return\n }\n\n // Too large to ever fit in the buffer, so give it a batch of its own.\n this.writeToFile(Buffer.from(`[${encodedEvent}]\\n`, 'utf8'))\n }\n\n /**\n * Append `[event` or `,event` to the buffer, returning false without\n * modifying it if the whole thing does not fit.\n */\n private tryWriteToBuffer(encodedEvent: string, capacity: number): boolean {\n // `[` opens a new batch, `,` separates events within one.\n const prefix = this.buffered === 0 ? '[' : ','\n const written = this.buffer.write(\n prefix + encodedEvent,\n this.buffered,\n capacity - this.buffered,\n 'utf8'\n )\n // `Buffer.write` truncates silently, so the byte count is the only signal\n // that the event did not fit -- and because it stops at the last whole\n // character, a truncated write can still leave a few bytes unused. Only a\n // write that ends clear of that margin is known to be complete.\n if (this.buffered + written > capacity - MAX_UTF8_CHAR_BYTES) {\n return false\n }\n this.buffered += written\n return true\n }\n\n flush(): void {\n if (this.buffered === 0) {\n return\n }\n this.buffered += TERMINATOR.copy(this.buffer, this.buffered)\n const data = this.buffer.subarray(0, this.buffered)\n this.buffered = 0\n this.writeToFile(data)\n }\n\n private writeToFile(data: Buffer): void {\n let offset = 0\n try {\n if (this.size + data.length > this.sizeLimit) {\n this.rotate()\n }\n const fd = this.open()\n // writeSync can write fewer than all the bytes\n while (offset < data.length) {\n offset += fs.writeSync(fd, data, offset)\n }\n } catch (err) {\n // Tracing is diagnostic, so a failed write should not fail the build.\n // N.B. This is incredibly rare and a torn write means the data may be corrupted on disk.\n console.log(err)\n }\n this.size += offset\n }\n\n /**\n * Release the descriptor without flushing. Callers that want the buffered\n * tail on disk flush first; `rotate` deliberately does not.\n */\n private closeFd(): void {\n if (this.fd === undefined) {\n return\n }\n try {\n fs.closeSync(this.fd)\n } catch {\n // Nothing useful to do if the descriptor is already gone.\n }\n this.fd = undefined\n }\n\n /**\n * Flush and release the descriptor. Only needed when something else has to\n * act on the file (Windows cannot remove a file that is still open), which\n * in practice means tests -- the normal lifetime of the process is the\n * lifetime of the trace.\n */\n close(): void {\n this.flush()\n this.closeFd()\n }\n}\n\nexport function createJsonReporter(options: {\n filename: string\n sizeLimit: number | ((phase: string) => number)\n filter?: (event: TraceEvent) => boolean\n}): Reporter {\n let writeStream: RotatingWriteStream | undefined\n\n function report(event: TraceEvent) {\n if (options.filter && !options.filter(event)) {\n return\n }\n\n const distDir = traceGlobals.get('distDir')\n const phase = traceGlobals.get('phase')\n if (!distDir || !phase) {\n return\n }\n\n const file = path.join(distDir, options.filename)\n // `distDir` can change within a process (most visibly between tests), so\n // a stream opened against a previous one must not keep receiving events.\n if (writeStream && writeStream.file !== file) {\n writeStream.close()\n writeStream = undefined\n }\n\n if (!writeStream) {\n // Constructing the stream touches no filesystem state -- the directory\n // and file are created lazily on the first write.\n const limit =\n typeof options.sizeLimit === 'function'\n ? options.sizeLimit(phase)\n : options.sizeLimit\n writeStream = new RotatingWriteStream(file, limit)\n }\n\n writeStream.write(JSON.stringify({ ...event, traceId }))\n }\n\n return {\n flushAll: () => writeStream?.flush(),\n close: () => {\n writeStream?.close()\n writeStream = undefined\n },\n report,\n }\n}\n\nexport default createJsonReporter({\n filename: 'trace',\n sizeLimit: (phase) =>\n // Development is limited to 50MB, production is unlimited\n phase === PHASE_DEVELOPMENT_SERVER ? 52428800 : Infinity,\n})\n"],"names":["createJsonReporter","BUFFER_SIZE","TERMINATOR","Buffer","from","MAX_UTF8_CHAR_BYTES","RotatingWriteStream","constructor","file","sizeLimit","buffer","allocUnsafe","buffered","size","open","fd","undefined","fs","mkdirSync","path","dirname","recursive","openSync","traceGlobals","get","PHASE_DEVELOPMENT_SERVER","rotate","closeFd","write","encodedEvent","capacity","length","tryWriteToBuffer","flush","writeToFile","prefix","written","copy","data","subarray","offset","writeSync","err","console","log","closeSync","close","options","writeStream","report","event","filter","distDir","phase","join","filename","limit","JSON","stringify","traceId","flushAll","Infinity"],"mappings":";;;;;;;;;;;;;;;IA6KgBA,kBAAkB;eAAlBA;;IAiDhB,OAKE;eALF;;;wBA9NsC;2DACvB;6DACE;2BACwB;;;;;;AAIzC,0EAA0E;AAC1E,+EAA+E;AAC/E,MAAMC,cAAc,KAAK;AACzB,4EAA4E;AAC5E,yCAAyC;AACzC,MAAMC,aAAaC,OAAOC,IAAI,CAAC,OAAO;AACtC,MAAMC,sBAAsB;AAE5B;;;;;;;;CAQC,GACD,MAAMC;IAWJC,YAAYC,IAAY,EAAEC,SAAiB,CAAE;aAP5BC,SAASP,OAAOQ,WAAW,CAACV;QAC7C,uEAAuE;QACvE,0CAA0C;aAClCW,WAAmB;aACnBC,OAAe;QAIrB,IAAI,CAACL,IAAI,GAAGA;QACZ,IAAI,CAACC,SAAS,GAAGA;QACjB,wEAAwE;QACxE,mCAAmC;QACnC,IAAI,CAACI,IAAI,GAAG;IACd;IAEA;;;;;GAKC,GACD,AAAQC,OAAe;QACrB,IAAI,IAAI,CAACC,EAAE,KAAKC,WAAW;YACzBC,WAAE,CAACC,SAAS,CAACC,aAAI,CAACC,OAAO,CAAC,IAAI,CAACZ,IAAI,GAAG;gBAAEa,WAAW;YAAK;YACxD,sEAAsE;YACtE,yDAAyD;YACzD,IAAI,CAACN,EAAE,GAAGE,WAAE,CAACK,QAAQ,CACnB,IAAI,CAACd,IAAI,EACTe,oBAAY,CAACC,GAAG,CAAC,aAAaC,mCAAwB,GAAG,MAAM;QAEnE;QACA,OAAO,IAAI,CAACV,EAAE;IAChB;IAEA,oBAAoB;IACZW,SAAS;QACf,IAAI,CAACC,OAAO;QACZV,WAAE,CAACC,SAAS,CAACC,aAAI,CAACC,OAAO,CAAC,IAAI,CAACZ,IAAI,GAAG;YAAEa,WAAW;QAAK;QACxD,uEAAuE;QACvE,IAAI,CAACN,EAAE,GAAGE,WAAE,CAACK,QAAQ,CAAC,IAAI,CAACd,IAAI,EAAE;QACjC,IAAI,CAACK,IAAI,GAAG;IACd;IAEA;;;;GAIC,GACDe,MAAMC,YAAoB,EAAQ;QAChC,MAAMC,WAAW,IAAI,CAACpB,MAAM,CAACqB,MAAM,GAAG7B,WAAW6B,MAAM;QACvD,IAAI,IAAI,CAACC,gBAAgB,CAACH,cAAcC,WAAW;YACjD;QACF;QAEA,iDAAiD;QACjD,IAAI,CAACG,KAAK;QACV,IAAI,IAAI,CAACD,gBAAgB,CAACH,cAAcC,WAAW;YACjD;QACF;QAEA,sEAAsE;QACtE,IAAI,CAACI,WAAW,CAAC/B,OAAOC,IAAI,CAAC,CAAC,CAAC,EAAEyB,aAAa,GAAG,CAAC,EAAE;IACtD;IAEA;;;GAGC,GACD,AAAQG,iBAAiBH,YAAoB,EAAEC,QAAgB,EAAW;QACxE,0DAA0D;QAC1D,MAAMK,SAAS,IAAI,CAACvB,QAAQ,KAAK,IAAI,MAAM;QAC3C,MAAMwB,UAAU,IAAI,CAAC1B,MAAM,CAACkB,KAAK,CAC/BO,SAASN,cACT,IAAI,CAACjB,QAAQ,EACbkB,WAAW,IAAI,CAAClB,QAAQ,EACxB;QAEF,0EAA0E;QAC1E,uEAAuE;QACvE,0EAA0E;QAC1E,gEAAgE;QAChE,IAAI,IAAI,CAACA,QAAQ,GAAGwB,UAAUN,WAAWzB,qBAAqB;YAC5D,OAAO;QACT;QACA,IAAI,CAACO,QAAQ,IAAIwB;QACjB,OAAO;IACT;IAEAH,QAAc;QACZ,IAAI,IAAI,CAACrB,QAAQ,KAAK,GAAG;YACvB;QACF;QACA,IAAI,CAACA,QAAQ,IAAIV,WAAWmC,IAAI,CAAC,IAAI,CAAC3B,MAAM,EAAE,IAAI,CAACE,QAAQ;QAC3D,MAAM0B,OAAO,IAAI,CAAC5B,MAAM,CAAC6B,QAAQ,CAAC,GAAG,IAAI,CAAC3B,QAAQ;QAClD,IAAI,CAACA,QAAQ,GAAG;QAChB,IAAI,CAACsB,WAAW,CAACI;IACnB;IAEQJ,YAAYI,IAAY,EAAQ;QACtC,IAAIE,SAAS;QACb,IAAI;YACF,IAAI,IAAI,CAAC3B,IAAI,GAAGyB,KAAKP,MAAM,GAAG,IAAI,CAACtB,SAAS,EAAE;gBAC5C,IAAI,CAACiB,MAAM;YACb;YACA,MAAMX,KAAK,IAAI,CAACD,IAAI;YACpB,+CAA+C;YAC/C,MAAO0B,SAASF,KAAKP,MAAM,CAAE;gBAC3BS,UAAUvB,WAAE,CAACwB,SAAS,CAAC1B,IAAIuB,MAAME;YACnC;QACF,EAAE,OAAOE,KAAK;YACZ,sEAAsE;YACtE,yFAAyF;YACzFC,QAAQC,GAAG,CAACF;QACd;QACA,IAAI,CAAC7B,IAAI,IAAI2B;IACf;IAEA;;;GAGC,GACD,AAAQb,UAAgB;QACtB,IAAI,IAAI,CAACZ,EAAE,KAAKC,WAAW;YACzB;QACF;QACA,IAAI;YACFC,WAAE,CAAC4B,SAAS,CAAC,IAAI,CAAC9B,EAAE;QACtB,EAAE,OAAM;QACN,0DAA0D;QAC5D;QACA,IAAI,CAACA,EAAE,GAAGC;IACZ;IAEA;;;;;GAKC,GACD8B,QAAc;QACZ,IAAI,CAACb,KAAK;QACV,IAAI,CAACN,OAAO;IACd;AACF;AAEO,SAAS3B,mBAAmB+C,OAIlC;IACC,IAAIC;IAEJ,SAASC,OAAOC,KAAiB;QAC/B,IAAIH,QAAQI,MAAM,IAAI,CAACJ,QAAQI,MAAM,CAACD,QAAQ;YAC5C;QACF;QAEA,MAAME,UAAU7B,oBAAY,CAACC,GAAG,CAAC;QACjC,MAAM6B,QAAQ9B,oBAAY,CAACC,GAAG,CAAC;QAC/B,IAAI,CAAC4B,WAAW,CAACC,OAAO;YACtB;QACF;QAEA,MAAM7C,OAAOW,aAAI,CAACmC,IAAI,CAACF,SAASL,QAAQQ,QAAQ;QAChD,yEAAyE;QACzE,yEAAyE;QACzE,IAAIP,eAAeA,YAAYxC,IAAI,KAAKA,MAAM;YAC5CwC,YAAYF,KAAK;YACjBE,cAAchC;QAChB;QAEA,IAAI,CAACgC,aAAa;YAChB,uEAAuE;YACvE,kDAAkD;YAClD,MAAMQ,QACJ,OAAOT,QAAQtC,SAAS,KAAK,aACzBsC,QAAQtC,SAAS,CAAC4C,SAClBN,QAAQtC,SAAS;YACvBuC,cAAc,IAAI1C,oBAAoBE,MAAMgD;QAC9C;QAEAR,YAAYpB,KAAK,CAAC6B,KAAKC,SAAS,CAAC;YAAE,GAAGR,KAAK;YAAES,SAAAA,eAAO;QAAC;IACvD;IAEA,OAAO;QACLC,UAAU,IAAMZ,+BAAAA,YAAaf,KAAK;QAClCa,OAAO;YACLE,+BAAAA,YAAaF,KAAK;YAClBE,cAAchC;QAChB;QACAiC;IACF;AACF;MAEA,WAAejD,mBAAmB;IAChCuD,UAAU;IACV9C,WAAW,CAAC4C,QACV,0DAA0D;QAC1DA,UAAU5B,mCAAwB,GAAG,WAAWoC;AACpD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/to-telemetry.d.ts b/e-commerce/node_modules/next/dist/trace/report/to-telemetry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2066f67ca10f0b994b8219f1dfcf0b6c8bb00409 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-telemetry.d.ts @@ -0,0 +1,6 @@ +import type { TraceEvent } from '../types'; +declare const _default: { + flushAll: () => void; + report: ({ name, duration }: TraceEvent) => void; +}; +export default _default; diff --git a/e-commerce/node_modules/next/dist/trace/report/to-telemetry.js b/e-commerce/node_modules/next/dist/trace/report/to-telemetry.js new file mode 100644 index 0000000000000000000000000000000000000000..473cf0d244670e4939175f90b111e0f5cd628a7b --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-telemetry.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _shared = require("../shared"); +const TRACE_EVENT_ACCESSLIST = new Map(Object.entries({ + 'webpack-invalidated': 'WEBPACK_INVALIDATED' +})); +const reportToTelemetry = ({ name, duration })=>{ + const eventName = TRACE_EVENT_ACCESSLIST.get(name); + if (!eventName) { + return; + } + const telemetry = _shared.traceGlobals.get('telemetry'); + if (!telemetry) { + return; + } + telemetry.record({ + eventName, + payload: { + durationInMicroseconds: duration + } + }); +}; +const _default = { + flushAll: ()=>{}, + report: reportToTelemetry +}; + +//# sourceMappingURL=to-telemetry.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/to-telemetry.js.map b/e-commerce/node_modules/next/dist/trace/report/to-telemetry.js.map new file mode 100644 index 0000000000000000000000000000000000000000..802a32582508684809e47e186c82e03b3a9fdec8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/to-telemetry.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/trace/report/to-telemetry.ts"],"sourcesContent":["import type { Telemetry } from '../../telemetry/storage'\nimport { traceGlobals } from '../shared'\nimport type { TraceEvent } from '../types'\n\nconst TRACE_EVENT_ACCESSLIST = new Map(\n Object.entries({\n 'webpack-invalidated': 'WEBPACK_INVALIDATED',\n })\n)\n\nconst reportToTelemetry = ({ name, duration }: TraceEvent) => {\n const eventName = TRACE_EVENT_ACCESSLIST.get(name)\n if (!eventName) {\n return\n }\n const telemetry: Telemetry | undefined = traceGlobals.get('telemetry')\n if (!telemetry) {\n return\n }\n\n telemetry.record({\n eventName,\n payload: {\n durationInMicroseconds: duration,\n },\n })\n}\n\nexport default {\n flushAll: () => {},\n report: reportToTelemetry,\n}\n"],"names":["TRACE_EVENT_ACCESSLIST","Map","Object","entries","reportToTelemetry","name","duration","eventName","get","telemetry","traceGlobals","record","payload","durationInMicroseconds","flushAll","report"],"mappings":";;;;+BA4BA;;;eAAA;;;wBA3B6B;AAG7B,MAAMA,yBAAyB,IAAIC,IACjCC,OAAOC,OAAO,CAAC;IACb,uBAAuB;AACzB;AAGF,MAAMC,oBAAoB,CAAC,EAAEC,IAAI,EAAEC,QAAQ,EAAc;IACvD,MAAMC,YAAYP,uBAAuBQ,GAAG,CAACH;IAC7C,IAAI,CAACE,WAAW;QACd;IACF;IACA,MAAME,YAAmCC,oBAAY,CAACF,GAAG,CAAC;IAC1D,IAAI,CAACC,WAAW;QACd;IACF;IAEAA,UAAUE,MAAM,CAAC;QACfJ;QACAK,SAAS;YACPC,wBAAwBP;QAC1B;IACF;AACF;MAEA,WAAe;IACbQ,UAAU,KAAO;IACjBC,QAAQX;AACV","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/types.d.ts b/e-commerce/node_modules/next/dist/trace/report/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..852ddb1d9a943353fc652ae2f71bf246226e51aa --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/types.d.ts @@ -0,0 +1,11 @@ +import type { TraceEvent } from '../types'; +export type Reporter = { + flushAll: () => void; + report: (event: TraceEvent) => void; + /** + * Release any file handles. Optional: only reporters that hold one need it, + * and only callers that must act on the file afterwards (tests removing a + * temp dir on Windows) need to call it. + */ + close?: () => void; +}; diff --git a/e-commerce/node_modules/next/dist/trace/report/types.js b/e-commerce/node_modules/next/dist/trace/report/types.js new file mode 100644 index 0000000000000000000000000000000000000000..f89b9ccce54e89b62b432c4802c4612600a703d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/report/types.js.map b/e-commerce/node_modules/next/dist/trace/report/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/report/types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/shared.d.ts b/e-commerce/node_modules/next/dist/trace/shared.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7daafc2ccce1d77866d481f49e9b5a89123c2a0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/shared.d.ts @@ -0,0 +1,3 @@ +export declare const traceGlobals: Map; +export declare const setGlobal: (key: any, val: any) => void; +export declare const traceId: string; diff --git a/e-commerce/node_modules/next/dist/trace/shared.js b/e-commerce/node_modules/next/dist/trace/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..842982532d3c5e458487828b850ff7bf228f2e60 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/shared.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + setGlobal: null, + traceGlobals: null, + traceId: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + setGlobal: function() { + return setGlobal; + }, + traceGlobals: function() { + return traceGlobals; + }, + traceId: function() { + return traceId; + } +}); +const _nodecrypto = require("node:crypto"); +let _traceGlobals = global._traceGlobals; +if (!_traceGlobals) { + _traceGlobals = new Map(); +} +global._traceGlobals = _traceGlobals; +const traceGlobals = _traceGlobals; +const setGlobal = (key, val)=>{ + traceGlobals.set(key, val); +}; +const traceId = process.env.TRACE_ID || process.env.NEXT_PRIVATE_TRACE_ID || (0, _nodecrypto.randomBytes)(8).toString('hex'); + +//# sourceMappingURL=shared.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/shared.js.map b/e-commerce/node_modules/next/dist/trace/shared.js.map new file mode 100644 index 0000000000000000000000000000000000000000..086ff343d00d1297c50e6eb4764b2cf125741102 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/shared.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/trace/shared.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\n\nlet _traceGlobals: Map = (global as any)._traceGlobals\n\nif (!_traceGlobals) {\n _traceGlobals = new Map()\n}\n;(global as any)._traceGlobals = _traceGlobals\n\nexport const traceGlobals: Map = _traceGlobals\nexport const setGlobal = (key: any, val: any) => {\n traceGlobals.set(key, val)\n}\n\nexport const traceId =\n process.env.TRACE_ID ||\n process.env.NEXT_PRIVATE_TRACE_ID ||\n randomBytes(8).toString('hex')\n"],"names":["setGlobal","traceGlobals","traceId","_traceGlobals","global","Map","key","val","set","process","env","TRACE_ID","NEXT_PRIVATE_TRACE_ID","randomBytes","toString"],"mappings":";;;;;;;;;;;;;;;;IAUaA,SAAS;eAATA;;IADAC,YAAY;eAAZA;;IAKAC,OAAO;eAAPA;;;4BAde;AAE5B,IAAIC,gBAA+B,AAACC,OAAeD,aAAa;AAEhE,IAAI,CAACA,eAAe;IAClBA,gBAAgB,IAAIE;AACtB;AACED,OAAeD,aAAa,GAAGA;AAE1B,MAAMF,eAA8BE;AACpC,MAAMH,YAAY,CAACM,KAAUC;IAClCN,aAAaO,GAAG,CAACF,KAAKC;AACxB;AAEO,MAAML,UACXO,QAAQC,GAAG,CAACC,QAAQ,IACpBF,QAAQC,GAAG,CAACE,qBAAqB,IACjCC,IAAAA,uBAAW,EAAC,GAAGC,QAAQ,CAAC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/trace-uploader.d.ts b/e-commerce/node_modules/next/dist/trace/trace-uploader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace-uploader.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/e-commerce/node_modules/next/dist/trace/trace-uploader.js b/e-commerce/node_modules/next/dist/trace/trace-uploader.js new file mode 100644 index 0000000000000000000000000000000000000000..4fc5b98899ab6ee8c57d440e74f397e1abf6ba5e --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace-uploader.js @@ -0,0 +1,182 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up")); +const _promises = /*#__PURE__*/ _interop_require_default(require("fs/promises")); +const _assert = /*#__PURE__*/ _interop_require_default(require("assert")); +const _os = /*#__PURE__*/ _interop_require_default(require("os")); +const _readline = require("readline"); +const _fs = require("fs"); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _git = require("../lib/helpers/git"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const COMMON_ALLOWED_EVENTS = [ + 'memory-usage', + 'turbopack-persistence', + 'turbopack-compaction', + 'turbopack-module-graph', + 'turbopack-write-entrypoints', + 'turbopack-emit' +]; +// Predefined set of the event names to be included in the trace. +// If the trace span's name matches to one of the event names in the set, +// it'll up uploaded to the trace server. +const DEV_ALLOWED_EVENTS = new Set([ + ...COMMON_ALLOWED_EVENTS, + 'client-hmr-latency', + 'render-path', + 'hot-reloader', + 'webpack-invalid-client', + 'webpack-invalidated-server', + 'navigation-to-hydration', + 'start-dev-server', + 'compile-path', + 'memory-usage', + 'server-restart-close-to-memory-threshold' +]); +const BUILD_ALLOWED_EVENTS = new Set([ + ...COMMON_ALLOWED_EVENTS, + 'next-build', + 'run-turbopack', + 'webpack-compilation', + 'run-webpack-compiler', + 'create-entrypoints', + 'worker-main-edge-server', + 'worker-main-client', + 'worker-main-server', + 'server', + 'make', + 'seal', + 'chunk-graph', + 'optimize-modules', + 'optimize-chunks', + 'optimize', + 'optimize-tree', + 'optimize-chunk-modules', + 'module-hash', + 'client', + 'static-check', + 'node-file-trace-build', + 'static-generation', + 'next-export', + 'run-typescript', + 'run-eslint' +]); +const { NEXT_TRACE_UPLOAD_DEBUG, // An external env to allow to upload full trace without picking up the relavant spans. +// This is mainly for the debugging purpose, to allow manual audit for full trace for the given build. +// [NOTE] This may fail if build is large and generated trace is excessively large. +NEXT_TRACE_UPLOAD_FULL } = process.env; +const isDebugEnabled = !!NEXT_TRACE_UPLOAD_DEBUG || !!NEXT_TRACE_UPLOAD_FULL; +const shouldUploadFullTrace = !!NEXT_TRACE_UPLOAD_FULL; +const [, , traceUploadUrl, mode, projectDir, distDir, _isTurboSession, traceId, anonymousId, sessionId] = process.argv; +const isTurboSession = _isTurboSession === 'true'; +(async function upload() { + const nextVersion = JSON.parse(await _promises.default.readFile(_path.default.resolve(__dirname, '../../package.json'), 'utf8')).version; + const projectPkgJsonPath = await (0, _findup.default)('package.json'); + (0, _assert.default)(projectPkgJsonPath); + const projectPkgJson = JSON.parse(await _promises.default.readFile(projectPkgJsonPath, 'utf-8')); + const pkgName = projectPkgJson.name; + const isVercelEnvironment = !!process.env.VERCEL; + const commit = (0, _git.getGitCommit)(projectDir) ?? ''; + const branch = (0, _git.getGitBranch)(projectDir) ?? ''; + const readLineInterface = (0, _readline.createInterface)({ + input: (0, _fs.createReadStream)(_path.default.join(projectDir, distDir, 'trace')), + crlfDelay: Infinity + }); + const sessionTrace = []; + let sessionEnabledFeatures = {}; + const spanEnabledFeatures = new Map(); + for await (const line of readLineInterface){ + const lineEvents = JSON.parse(line); + for (const event of lineEvents){ + if (event.traceId !== traceId) { + continue; + } + // Extract enabled features from the root span (next-dev or next-build) + if (event.parentId === undefined && event.tags && (event.name === 'next-dev' || event.name === 'next-build')) { + for (const [key, value] of Object.entries(event.tags)){ + if (key.startsWith('feature.')) { + sessionEnabledFeatures[key] = value; + } + } + } + // Collect feature tags from all events for inheritance + if (event.tags) { + const enabledFeatures = {}; + for (const [key, value] of Object.entries(event.tags)){ + if (key.startsWith('feature.')) { + enabledFeatures[key] = value; + } + } + if (Object.keys(enabledFeatures).length > 0) { + spanEnabledFeatures.set(event.id, enabledFeatures); + } + } + if (// Always include root spans + event.parentId === undefined || shouldUploadFullTrace || (mode === 'dev' ? DEV_ALLOWED_EVENTS.has(event.name) : BUILD_ALLOWED_EVENTS.has(event.name))) { + sessionTrace.push(event); + } + } + } + // Apply feature tag inheritance to session trace + const sessionTraceWithInheritance = sessionTrace.map((event)=>{ + if (event.parentId !== undefined) { + const parentFlags = spanEnabledFeatures.get(event.parentId); + if (parentFlags && Object.keys(parentFlags).length > 0) { + // Inherit parent flags, but child's own tags take precedence + return { + ...event, + tags: { + ...parentFlags, + ...event.tags + } + }; + } + } + return event; + }); + const body = { + metadata: { + anonymousId, + arch: _os.default.arch(), + branch, + commit, + cpus: _os.default.cpus().length, + isVercelEnvironment, + isTurboSession, + mode, + nextVersion, + pkgName, + platform: _os.default.platform(), + sessionId, + enabledFeatures: sessionEnabledFeatures + }, + // The trace file can contain events spanning multiple sessions. + // Only submit traces for the current session, as the metadata we send is + // intended for this session only. + traces: [ + sessionTraceWithInheritance + ] + }; + if (isDebugEnabled) { + console.log('Sending request with body', JSON.stringify(body, null, 2)); + } + let res = await fetch(traceUploadUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-trace-transfer-mode': shouldUploadFullTrace ? 'full' : 'default' + }, + body: JSON.stringify(body) + }); + if (isDebugEnabled) { + console.log('Received response', res.status, await res.json()); + } +})(); + +//# sourceMappingURL=trace-uploader.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/trace-uploader.js.map b/e-commerce/node_modules/next/dist/trace/trace-uploader.js.map new file mode 100644 index 0000000000000000000000000000000000000000..36dd9dc1f08f4338ab07d00443281629ee3c8ea6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace-uploader.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/trace/trace-uploader.ts"],"sourcesContent":["import findUp from 'next/dist/compiled/find-up'\nimport fsPromise from 'fs/promises'\nimport assert from 'assert'\nimport os from 'os'\nimport { createInterface } from 'readline'\nimport { createReadStream } from 'fs'\nimport path from 'path'\nimport { getGitBranch, getGitCommit } from '../lib/helpers/git'\n\nconst COMMON_ALLOWED_EVENTS = [\n 'memory-usage',\n 'turbopack-persistence',\n 'turbopack-compaction',\n 'turbopack-module-graph',\n 'turbopack-write-entrypoints',\n 'turbopack-emit',\n]\n\n// Predefined set of the event names to be included in the trace.\n// If the trace span's name matches to one of the event names in the set,\n// it'll up uploaded to the trace server.\nconst DEV_ALLOWED_EVENTS = new Set([\n ...COMMON_ALLOWED_EVENTS,\n 'client-hmr-latency',\n 'render-path',\n 'hot-reloader',\n 'webpack-invalid-client',\n 'webpack-invalidated-server',\n 'navigation-to-hydration',\n 'start-dev-server',\n 'compile-path',\n 'memory-usage',\n 'server-restart-close-to-memory-threshold',\n])\n\nconst BUILD_ALLOWED_EVENTS = new Set([\n ...COMMON_ALLOWED_EVENTS,\n 'next-build',\n 'run-turbopack',\n 'webpack-compilation',\n 'run-webpack-compiler',\n 'create-entrypoints',\n 'worker-main-edge-server',\n 'worker-main-client',\n 'worker-main-server',\n 'server',\n 'make',\n 'seal',\n 'chunk-graph',\n 'optimize-modules',\n 'optimize-chunks',\n 'optimize',\n 'optimize-tree',\n 'optimize-chunk-modules',\n 'module-hash',\n 'client',\n 'static-check',\n 'node-file-trace-build',\n 'static-generation',\n 'next-export',\n 'run-typescript',\n 'run-eslint',\n])\n\nconst {\n NEXT_TRACE_UPLOAD_DEBUG,\n // An external env to allow to upload full trace without picking up the relavant spans.\n // This is mainly for the debugging purpose, to allow manual audit for full trace for the given build.\n // [NOTE] This may fail if build is large and generated trace is excessively large.\n NEXT_TRACE_UPLOAD_FULL,\n} = process.env\n\nconst isDebugEnabled = !!NEXT_TRACE_UPLOAD_DEBUG || !!NEXT_TRACE_UPLOAD_FULL\nconst shouldUploadFullTrace = !!NEXT_TRACE_UPLOAD_FULL\n\nconst [\n ,\n ,\n traceUploadUrl,\n mode,\n projectDir,\n distDir,\n _isTurboSession,\n traceId,\n anonymousId,\n sessionId,\n] = process.argv\nconst isTurboSession = _isTurboSession === 'true'\n\ntype TraceRequestBody = {\n metadata: TraceMetadata\n traces: TraceEvent[][]\n}\n\ninterface TraceEvent {\n traceId: string\n parentId?: number\n name: string\n id: number\n startTime: number\n timestamp: number\n duration: number\n tags: Record\n}\n\ninterface TraceMetadata {\n anonymousId: string\n arch: string\n branch: string\n commit: string\n cpus: number\n isVercelEnvironment: boolean\n isTurboSession: boolean\n mode: string\n nextVersion: string\n pkgName: string\n platform: string\n sessionId: string\n enabledFeatures: Record\n}\n\n;(async function upload() {\n const nextVersion = JSON.parse(\n await fsPromise.readFile(\n path.resolve(__dirname, '../../package.json'),\n 'utf8'\n )\n ).version\n\n const projectPkgJsonPath = await findUp('package.json')\n assert(projectPkgJsonPath)\n\n const projectPkgJson = JSON.parse(\n await fsPromise.readFile(projectPkgJsonPath, 'utf-8')\n )\n const pkgName = projectPkgJson.name\n\n const isVercelEnvironment = !!process.env.VERCEL\n\n const commit = getGitCommit(projectDir) ?? ''\n\n const branch = getGitBranch(projectDir) ?? ''\n\n const readLineInterface = createInterface({\n input: createReadStream(path.join(projectDir, distDir, 'trace')),\n crlfDelay: Infinity,\n })\n\n const sessionTrace = []\n let sessionEnabledFeatures: Record = {}\n const spanEnabledFeatures = new Map>()\n\n for await (const line of readLineInterface) {\n const lineEvents: TraceEvent[] = JSON.parse(line)\n for (const event of lineEvents) {\n if (event.traceId !== traceId) {\n // Only consider events for the current session\n continue\n }\n\n // Extract enabled features from the root span (next-dev or next-build)\n if (\n event.parentId === undefined &&\n event.tags &&\n (event.name === 'next-dev' || event.name === 'next-build')\n ) {\n for (const [key, value] of Object.entries(event.tags)) {\n if (key.startsWith('feature.')) {\n sessionEnabledFeatures[key] = value\n }\n }\n }\n\n // Collect feature tags from all events for inheritance\n if (event.tags) {\n const enabledFeatures: Record = {}\n for (const [key, value] of Object.entries(event.tags)) {\n if (key.startsWith('feature.')) {\n enabledFeatures[key] = value\n }\n }\n if (Object.keys(enabledFeatures).length > 0) {\n spanEnabledFeatures.set(event.id, enabledFeatures)\n }\n }\n\n if (\n // Always include root spans\n event.parentId === undefined ||\n shouldUploadFullTrace ||\n (mode === 'dev'\n ? DEV_ALLOWED_EVENTS.has(event.name)\n : BUILD_ALLOWED_EVENTS.has(event.name))\n ) {\n sessionTrace.push(event)\n }\n }\n }\n\n // Apply feature tag inheritance to session trace\n const sessionTraceWithInheritance = sessionTrace.map((event) => {\n if (event.parentId !== undefined) {\n const parentFlags = spanEnabledFeatures.get(event.parentId)\n if (parentFlags && Object.keys(parentFlags).length > 0) {\n // Inherit parent flags, but child's own tags take precedence\n return { ...event, tags: { ...parentFlags, ...event.tags } }\n }\n }\n return event\n })\n\n const body: TraceRequestBody = {\n metadata: {\n anonymousId,\n arch: os.arch(),\n branch,\n commit,\n cpus: os.cpus().length,\n isVercelEnvironment,\n isTurboSession,\n mode,\n nextVersion,\n pkgName,\n platform: os.platform(),\n sessionId,\n enabledFeatures: sessionEnabledFeatures,\n },\n // The trace file can contain events spanning multiple sessions.\n // Only submit traces for the current session, as the metadata we send is\n // intended for this session only.\n traces: [sessionTraceWithInheritance],\n }\n\n if (isDebugEnabled) {\n console.log('Sending request with body', JSON.stringify(body, null, 2))\n }\n\n let res = await fetch(traceUploadUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-trace-transfer-mode': shouldUploadFullTrace ? 'full' : 'default',\n },\n body: JSON.stringify(body),\n })\n\n if (isDebugEnabled) {\n console.log('Received response', res.status, await res.json())\n }\n})()\n"],"names":["COMMON_ALLOWED_EVENTS","DEV_ALLOWED_EVENTS","Set","BUILD_ALLOWED_EVENTS","NEXT_TRACE_UPLOAD_DEBUG","NEXT_TRACE_UPLOAD_FULL","process","env","isDebugEnabled","shouldUploadFullTrace","traceUploadUrl","mode","projectDir","distDir","_isTurboSession","traceId","anonymousId","sessionId","argv","isTurboSession","upload","nextVersion","JSON","parse","fsPromise","readFile","path","resolve","__dirname","version","projectPkgJsonPath","findUp","assert","projectPkgJson","pkgName","name","isVercelEnvironment","VERCEL","commit","getGitCommit","branch","getGitBranch","readLineInterface","createInterface","input","createReadStream","join","crlfDelay","Infinity","sessionTrace","sessionEnabledFeatures","spanEnabledFeatures","Map","line","lineEvents","event","parentId","undefined","tags","key","value","Object","entries","startsWith","enabledFeatures","keys","length","set","id","has","push","sessionTraceWithInheritance","map","parentFlags","get","body","metadata","arch","os","cpus","platform","traces","console","log","stringify","res","fetch","method","headers","status","json"],"mappings":";;;;+DAAmB;iEACG;+DACH;2DACJ;0BACiB;oBACC;6DAChB;qBAC0B;;;;;;AAE3C,MAAMA,wBAAwB;IAC5B;IACA;IACA;IACA;IACA;IACA;CACD;AAED,iEAAiE;AACjE,yEAAyE;AACzE,yCAAyC;AACzC,MAAMC,qBAAqB,IAAIC,IAAI;OAC9BF;IACH;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMG,uBAAuB,IAAID,IAAI;OAChCF;IACH;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAM,EACJI,uBAAuB,EACvB,uFAAuF;AACvF,sGAAsG;AACtG,mFAAmF;AACnFC,sBAAsB,EACvB,GAAGC,QAAQC,GAAG;AAEf,MAAMC,iBAAiB,CAAC,CAACJ,2BAA2B,CAAC,CAACC;AACtD,MAAMI,wBAAwB,CAAC,CAACJ;AAEhC,MAAM,KAGJK,gBACAC,MACAC,YACAC,SACAC,iBACAC,SACAC,aACAC,UACD,GAAGX,QAAQY,IAAI;AAChB,MAAMC,iBAAiBL,oBAAoB;AAkCzC,CAAA,eAAeM;IACf,MAAMC,cAAcC,KAAKC,KAAK,CAC5B,MAAMC,iBAAS,CAACC,QAAQ,CACtBC,aAAI,CAACC,OAAO,CAACC,WAAW,uBACxB,SAEFC,OAAO;IAET,MAAMC,qBAAqB,MAAMC,IAAAA,eAAM,EAAC;IACxCC,IAAAA,eAAM,EAACF;IAEP,MAAMG,iBAAiBX,KAAKC,KAAK,CAC/B,MAAMC,iBAAS,CAACC,QAAQ,CAACK,oBAAoB;IAE/C,MAAMI,UAAUD,eAAeE,IAAI;IAEnC,MAAMC,sBAAsB,CAAC,CAAC9B,QAAQC,GAAG,CAAC8B,MAAM;IAEhD,MAAMC,SAASC,IAAAA,iBAAY,EAAC3B,eAAe;IAE3C,MAAM4B,SAASC,IAAAA,iBAAY,EAAC7B,eAAe;IAE3C,MAAM8B,oBAAoBC,IAAAA,yBAAe,EAAC;QACxCC,OAAOC,IAAAA,oBAAgB,EAACnB,aAAI,CAACoB,IAAI,CAAClC,YAAYC,SAAS;QACvDkC,WAAWC;IACb;IAEA,MAAMC,eAAe,EAAE;IACvB,IAAIC,yBAAkD,CAAC;IACvD,MAAMC,sBAAsB,IAAIC;IAEhC,WAAW,MAAMC,QAAQX,kBAAmB;QAC1C,MAAMY,aAA2BhC,KAAKC,KAAK,CAAC8B;QAC5C,KAAK,MAAME,SAASD,WAAY;YAC9B,IAAIC,MAAMxC,OAAO,KAAKA,SAAS;gBAE7B;YACF;YAEA,uEAAuE;YACvE,IACEwC,MAAMC,QAAQ,KAAKC,aACnBF,MAAMG,IAAI,IACTH,CAAAA,MAAMpB,IAAI,KAAK,cAAcoB,MAAMpB,IAAI,KAAK,YAAW,GACxD;gBACA,KAAK,MAAM,CAACwB,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACP,MAAMG,IAAI,EAAG;oBACrD,IAAIC,IAAII,UAAU,CAAC,aAAa;wBAC9Bb,sBAAsB,CAACS,IAAI,GAAGC;oBAChC;gBACF;YACF;YAEA,uDAAuD;YACvD,IAAIL,MAAMG,IAAI,EAAE;gBACd,MAAMM,kBAA2C,CAAC;gBAClD,KAAK,MAAM,CAACL,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACP,MAAMG,IAAI,EAAG;oBACrD,IAAIC,IAAII,UAAU,CAAC,aAAa;wBAC9BC,eAAe,CAACL,IAAI,GAAGC;oBACzB;gBACF;gBACA,IAAIC,OAAOI,IAAI,CAACD,iBAAiBE,MAAM,GAAG,GAAG;oBAC3Cf,oBAAoBgB,GAAG,CAACZ,MAAMa,EAAE,EAAEJ;gBACpC;YACF;YAEA,IACE,4BAA4B;YAC5BT,MAAMC,QAAQ,KAAKC,aACnBhD,yBACCE,CAAAA,SAAS,QACNV,mBAAmBoE,GAAG,CAACd,MAAMpB,IAAI,IACjChC,qBAAqBkE,GAAG,CAACd,MAAMpB,IAAI,CAAA,GACvC;gBACAc,aAAaqB,IAAI,CAACf;YACpB;QACF;IACF;IAEA,iDAAiD;IACjD,MAAMgB,8BAA8BtB,aAAauB,GAAG,CAAC,CAACjB;QACpD,IAAIA,MAAMC,QAAQ,KAAKC,WAAW;YAChC,MAAMgB,cAActB,oBAAoBuB,GAAG,CAACnB,MAAMC,QAAQ;YAC1D,IAAIiB,eAAeZ,OAAOI,IAAI,CAACQ,aAAaP,MAAM,GAAG,GAAG;gBACtD,6DAA6D;gBAC7D,OAAO;oBAAE,GAAGX,KAAK;oBAAEG,MAAM;wBAAE,GAAGe,WAAW;wBAAE,GAAGlB,MAAMG,IAAI;oBAAC;gBAAE;YAC7D;QACF;QACA,OAAOH;IACT;IAEA,MAAMoB,OAAyB;QAC7BC,UAAU;YACR5D;YACA6D,MAAMC,WAAE,CAACD,IAAI;YACbrC;YACAF;YACAyC,MAAMD,WAAE,CAACC,IAAI,GAAGb,MAAM;YACtB9B;YACAjB;YACAR;YACAU;YACAa;YACA8C,UAAUF,WAAE,CAACE,QAAQ;YACrB/D;YACA+C,iBAAiBd;QACnB;QACA,gEAAgE;QAChE,yEAAyE;QACzE,kCAAkC;QAClC+B,QAAQ;YAACV;SAA4B;IACvC;IAEA,IAAI/D,gBAAgB;QAClB0E,QAAQC,GAAG,CAAC,6BAA6B7D,KAAK8D,SAAS,CAACT,MAAM,MAAM;IACtE;IAEA,IAAIU,MAAM,MAAMC,MAAM5E,gBAAgB;QACpC6E,QAAQ;QACRC,SAAS;YACP,gBAAgB;YAChB,yBAAyB/E,wBAAwB,SAAS;QAC5D;QACAkE,MAAMrD,KAAK8D,SAAS,CAACT;IACvB;IAEA,IAAInE,gBAAgB;QAClB0E,QAAQC,GAAG,CAAC,qBAAqBE,IAAII,MAAM,EAAE,MAAMJ,IAAIK,IAAI;IAC7D;AACF,CAAA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/trace.d.ts b/e-commerce/node_modules/next/dist/trace/trace.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..534b03037f22c0efb393a42b82ebcbc88d35c061 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace.d.ts @@ -0,0 +1,56 @@ +import type { SpanId, TraceEvent, TraceState } from './types'; +export declare enum SpanStatus { + Started = "started", + Stopped = "stopped" +} +interface Attributes { + [key: string]: unknown; +} +export declare class Span { + private name; + private id; + private parentId?; + private attrs; + private status; + private now; + private _start; + constructor({ name, parentId, attrs, startTime, wallStartTimeMs, }: { + name: string; + parentId?: SpanId; + startTime?: bigint; + wallStartTimeMs?: number; + attrs?: Attributes; + }); + stop(stopTime?: bigint): void; + traceChild(name: string, attrs?: Attributes): Span; + manualTraceChild(name: string, startTime?: bigint, stopTime?: bigint, attrs?: Attributes): void; + getId(): number; + setAttribute(key: string, value: unknown): void; + traceFn(fn: (span: Span) => T): T; + traceAsyncFn(fn: (span: Span) => T | Promise): Promise; +} +export declare const trace: (name: string, parentId?: SpanId, attrs?: { + [key: string]: unknown; +}) => Span; +export declare const flushAllTraces: () => void; +/** + * Flush and release the trace file handle. Intended for tests that need to + * delete the directory holding the trace afterwards. + */ +export declare const closeAllTraces: () => void; +export declare const exportTraceState: () => TraceState; +export declare const initializeTraceState: (state: TraceState) => void; +export declare function getTraceEvents(): TraceEvent[]; +export declare function recordTraceEvents(events: TraceEvent[]): void; +export declare const clearTraceEvents: () => never[]; +/** + * Converts hrtime (process.hrtime.bigint()) to epoch-based nanoseconds. + * + * hrtime values are relative to an arbitrary point in the past, while + * epoch-based times are nanoseconds since Unix epoch (Jan 1, 1970). + * + * This is useful when passing hrtime values to APIs that expect epoch-based times, + * such as Span.manualTraceChild(). + */ +export declare function hrtimeToEpochNanoseconds(hrtimeValue: bigint): bigint; +export {}; diff --git a/e-commerce/node_modules/next/dist/trace/trace.js b/e-commerce/node_modules/next/dist/trace/trace.js new file mode 100644 index 0000000000000000000000000000000000000000..103d16dd0ce5a5616b40a77881b3ea329d734df2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace.js @@ -0,0 +1,216 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + Span: null, + SpanStatus: null, + clearTraceEvents: null, + closeAllTraces: null, + exportTraceState: null, + flushAllTraces: null, + getTraceEvents: null, + hrtimeToEpochNanoseconds: null, + initializeTraceState: null, + recordTraceEvents: null, + trace: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + Span: function() { + return Span; + }, + SpanStatus: function() { + return SpanStatus; + }, + clearTraceEvents: function() { + return clearTraceEvents; + }, + closeAllTraces: function() { + return closeAllTraces; + }, + exportTraceState: function() { + return exportTraceState; + }, + flushAllTraces: function() { + return flushAllTraces; + }, + getTraceEvents: function() { + return getTraceEvents; + }, + hrtimeToEpochNanoseconds: function() { + return hrtimeToEpochNanoseconds; + }, + initializeTraceState: function() { + return initializeTraceState; + }, + recordTraceEvents: function() { + return recordTraceEvents; + }, + trace: function() { + return trace; + } +}); +const _report = require("./report"); +const NUM_OF_MICROSEC_IN_NANOSEC = BigInt('1000'); +const NUM_OF_MILLISEC_IN_NANOSEC = BigInt('1000000'); +let count = 0; +const getId = ()=>{ + count++; + return count; +}; +let defaultParentSpanId; +let shouldSaveTraceEvents; +let savedTraceEvents = []; +const RECORD_SPAN_THRESHOLD_MS = parseInt(process.env.NEXT_TRACE_SPAN_THRESHOLD_MS ?? '-1'); +var SpanStatus = /*#__PURE__*/ function(SpanStatus) { + SpanStatus["Started"] = "started"; + SpanStatus["Stopped"] = "stopped"; + return SpanStatus; +}({}); +class Span { + constructor({ name, parentId, attrs, startTime, wallStartTimeMs }){ + this.name = name; + this.parentId = parentId ?? defaultParentSpanId; + this.attrs = attrs ? { + ...attrs + } : {}; + this.status = "started"; + this.id = getId(); + this._start = startTime || process.hrtime.bigint(); + // hrtime cannot be used to reconstruct tracing span's actual start time + // since it does not have relation to clock time: + // `These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift` + // https://nodejs.org/api/process.html#processhrtimetime + // Capturing current datetime as additional metadata for external reconstruction. + this.now = wallStartTimeMs ?? Date.now(); + } + // Durations are reported as microseconds. This gives 1000x the precision + // of something like Date.now(), which reports in milliseconds. + // Additionally, ~285 years can be safely represented as microseconds as + // a float64 in both JSON and JavaScript. + stop(stopTime) { + if (this.status === "stopped") { + // Don't report the same span twice. + // TODO: In the future this should throw as `.stop()` shouldn't be called multiple times. + return; + } + const end = stopTime || process.hrtime.bigint(); + const duration = (end - this._start) / NUM_OF_MICROSEC_IN_NANOSEC; + this.status = "stopped"; + if (duration > Number.MAX_SAFE_INTEGER) { + throw new Error(`Duration is too long to express as float64: ${duration}`); + } + const timestamp = this._start / NUM_OF_MICROSEC_IN_NANOSEC; + const traceEvent = { + name: this.name, + duration: Number(duration), + timestamp: Number(timestamp), + id: this.id, + parentId: this.parentId, + tags: this.attrs, + startTime: this.now + }; + if (duration > RECORD_SPAN_THRESHOLD_MS * 1000) { + _report.reporter.report(traceEvent); + if (shouldSaveTraceEvents) { + savedTraceEvents.push(traceEvent); + } + } + } + traceChild(name, attrs) { + return new Span({ + name, + parentId: this.id, + attrs + }); + } + manualTraceChild(name, // Start time in nanoseconds since epoch. + startTime, // Stop time in nanoseconds since epoch. + stopTime, attrs) { + // We need to convert the time info to the same base as hrtime since that is used usually. + const correction = process.hrtime.bigint() - BigInt(Date.now()) * NUM_OF_MILLISEC_IN_NANOSEC; + const span = new Span({ + name, + parentId: this.id, + attrs, + startTime: startTime ? startTime + correction : process.hrtime.bigint(), + // The span is constructed when the event is recorded, which may be long + // after the work started (e.g. compilation events forwarded from + // Turbopack), so derive the wall-clock start from the given epoch time. + wallStartTimeMs: startTime ? Number(startTime / NUM_OF_MILLISEC_IN_NANOSEC) : undefined + }); + span.stop(stopTime ? stopTime + correction : process.hrtime.bigint()); + } + getId() { + return this.id; + } + setAttribute(key, value) { + this.attrs[key] = value; + } + traceFn(fn) { + try { + return fn(this); + } catch (e) { + this.attrs['failed'] = true; + throw e; + } finally{ + this.stop(); + } + } + async traceAsyncFn(fn) { + try { + return await fn(this); + } catch (e) { + this.attrs['failed'] = true; + throw e; + } finally{ + this.stop(); + } + } +} +const trace = (name, parentId, attrs)=>{ + return new Span({ + name, + parentId, + attrs + }); +}; +const flushAllTraces = ()=>_report.reporter.flushAll(); +const closeAllTraces = ()=>_report.reporter.close(); +const exportTraceState = ()=>({ + defaultParentSpanId, + lastId: count, + shouldSaveTraceEvents + }); +const initializeTraceState = (state)=>{ + count = state.lastId; + defaultParentSpanId = state.defaultParentSpanId; + shouldSaveTraceEvents = state.shouldSaveTraceEvents; +}; +function getTraceEvents() { + return savedTraceEvents; +} +function recordTraceEvents(events) { + for (const traceEvent of events){ + _report.reporter.report(traceEvent); + if (traceEvent.id > count) { + count = traceEvent.id + 1; + } + } + if (shouldSaveTraceEvents) { + savedTraceEvents.push(...events); + } +} +const clearTraceEvents = ()=>savedTraceEvents = []; +function hrtimeToEpochNanoseconds(hrtimeValue) { + const offset = BigInt(Date.now()) * NUM_OF_MILLISEC_IN_NANOSEC - process.hrtime.bigint(); + return hrtimeValue + offset; +} + +//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/trace.js.map b/e-commerce/node_modules/next/dist/trace/trace.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3cd49ec8b4d400555082d12743643801eac9efa7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/trace/trace.ts"],"sourcesContent":["import { reporter } from './report'\nimport type { SpanId, TraceEvent, TraceState } from './types'\n\nconst NUM_OF_MICROSEC_IN_NANOSEC = BigInt('1000')\nconst NUM_OF_MILLISEC_IN_NANOSEC = BigInt('1000000')\n\nlet count = 0\nconst getId = () => {\n count++\n return count\n}\nlet defaultParentSpanId: SpanId | undefined\nlet shouldSaveTraceEvents: boolean | undefined\nlet savedTraceEvents: TraceEvent[] = []\n\nconst RECORD_SPAN_THRESHOLD_MS = parseInt(\n process.env.NEXT_TRACE_SPAN_THRESHOLD_MS ?? '-1'\n)\n\n// eslint typescript has a bug with TS enums\nexport enum SpanStatus {\n Started = 'started',\n Stopped = 'stopped',\n}\n\ninterface Attributes {\n [key: string]: unknown\n}\n\nexport class Span {\n private name: string\n private id: SpanId\n private parentId?: SpanId\n private attrs: { [key: string]: unknown }\n private status: SpanStatus\n private now: number\n\n // Number of nanoseconds since epoch.\n private _start: bigint\n\n constructor({\n name,\n parentId,\n attrs,\n startTime,\n wallStartTimeMs,\n }: {\n name: string\n parentId?: SpanId\n startTime?: bigint\n // Wall-clock start time in milliseconds since epoch, matching `startTime`.\n // Defaults to the construction time.\n wallStartTimeMs?: number\n attrs?: Attributes\n }) {\n this.name = name\n this.parentId = parentId ?? defaultParentSpanId\n this.attrs = attrs ? { ...attrs } : {}\n\n this.status = SpanStatus.Started\n this.id = getId()\n this._start = startTime || process.hrtime.bigint()\n // hrtime cannot be used to reconstruct tracing span's actual start time\n // since it does not have relation to clock time:\n // `These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift`\n // https://nodejs.org/api/process.html#processhrtimetime\n // Capturing current datetime as additional metadata for external reconstruction.\n this.now = wallStartTimeMs ?? Date.now()\n }\n\n // Durations are reported as microseconds. This gives 1000x the precision\n // of something like Date.now(), which reports in milliseconds.\n // Additionally, ~285 years can be safely represented as microseconds as\n // a float64 in both JSON and JavaScript.\n stop(stopTime?: bigint) {\n if (this.status === SpanStatus.Stopped) {\n // Don't report the same span twice.\n // TODO: In the future this should throw as `.stop()` shouldn't be called multiple times.\n return\n }\n const end: bigint = stopTime || process.hrtime.bigint()\n const duration = (end - this._start) / NUM_OF_MICROSEC_IN_NANOSEC\n this.status = SpanStatus.Stopped\n if (duration > Number.MAX_SAFE_INTEGER) {\n throw new Error(`Duration is too long to express as float64: ${duration}`)\n }\n const timestamp = this._start / NUM_OF_MICROSEC_IN_NANOSEC\n const traceEvent: TraceEvent = {\n name: this.name,\n duration: Number(duration),\n timestamp: Number(timestamp),\n id: this.id,\n parentId: this.parentId,\n tags: this.attrs,\n startTime: this.now,\n }\n if (duration > RECORD_SPAN_THRESHOLD_MS * 1000) {\n reporter.report(traceEvent)\n if (shouldSaveTraceEvents) {\n savedTraceEvents.push(traceEvent)\n }\n }\n }\n\n traceChild(name: string, attrs?: Attributes) {\n return new Span({ name, parentId: this.id, attrs })\n }\n\n manualTraceChild(\n name: string,\n // Start time in nanoseconds since epoch.\n startTime?: bigint,\n // Stop time in nanoseconds since epoch.\n stopTime?: bigint,\n attrs?: Attributes\n ) {\n // We need to convert the time info to the same base as hrtime since that is used usually.\n const correction =\n process.hrtime.bigint() - BigInt(Date.now()) * NUM_OF_MILLISEC_IN_NANOSEC\n const span = new Span({\n name,\n parentId: this.id,\n attrs,\n startTime: startTime ? startTime + correction : process.hrtime.bigint(),\n // The span is constructed when the event is recorded, which may be long\n // after the work started (e.g. compilation events forwarded from\n // Turbopack), so derive the wall-clock start from the given epoch time.\n wallStartTimeMs: startTime\n ? Number(startTime / NUM_OF_MILLISEC_IN_NANOSEC)\n : undefined,\n })\n span.stop(stopTime ? stopTime + correction : process.hrtime.bigint())\n }\n\n getId() {\n return this.id\n }\n\n setAttribute(key: string, value: unknown) {\n this.attrs[key] = value\n }\n\n traceFn(fn: (span: Span) => T): T {\n try {\n return fn(this)\n } catch (e) {\n this.attrs['failed'] = true\n throw e\n } finally {\n this.stop()\n }\n }\n\n async traceAsyncFn(fn: (span: Span) => T | Promise): Promise {\n try {\n return await fn(this)\n } catch (e) {\n this.attrs['failed'] = true\n throw e\n } finally {\n this.stop()\n }\n }\n}\n\nexport const trace = (\n name: string,\n parentId?: SpanId,\n attrs?: { [key: string]: unknown }\n) => {\n return new Span({ name, parentId, attrs })\n}\n\nexport const flushAllTraces = () => reporter.flushAll()\n\n/**\n * Flush and release the trace file handle. Intended for tests that need to\n * delete the directory holding the trace afterwards.\n */\nexport const closeAllTraces = () => reporter.close()\n\n// This code supports workers by serializing the state of tracers when the\n// worker is initialized, and serializing the trace events from the worker back\n// to the main process to record when the worker is complete.\nexport const exportTraceState = (): TraceState => ({\n defaultParentSpanId,\n lastId: count,\n shouldSaveTraceEvents,\n})\nexport const initializeTraceState = (state: TraceState) => {\n count = state.lastId\n defaultParentSpanId = state.defaultParentSpanId\n shouldSaveTraceEvents = state.shouldSaveTraceEvents\n}\n\nexport function getTraceEvents(): TraceEvent[] {\n return savedTraceEvents\n}\n\nexport function recordTraceEvents(events: TraceEvent[]) {\n for (const traceEvent of events) {\n reporter.report(traceEvent)\n if (traceEvent.id > count) {\n count = traceEvent.id + 1\n }\n }\n if (shouldSaveTraceEvents) {\n savedTraceEvents.push(...events)\n }\n}\n\nexport const clearTraceEvents = () => (savedTraceEvents = [])\n\n/**\n * Converts hrtime (process.hrtime.bigint()) to epoch-based nanoseconds.\n *\n * hrtime values are relative to an arbitrary point in the past, while\n * epoch-based times are nanoseconds since Unix epoch (Jan 1, 1970).\n *\n * This is useful when passing hrtime values to APIs that expect epoch-based times,\n * such as Span.manualTraceChild().\n */\nexport function hrtimeToEpochNanoseconds(hrtimeValue: bigint): bigint {\n const offset =\n BigInt(Date.now()) * NUM_OF_MILLISEC_IN_NANOSEC - process.hrtime.bigint()\n return hrtimeValue + offset\n}\n"],"names":["Span","SpanStatus","clearTraceEvents","closeAllTraces","exportTraceState","flushAllTraces","getTraceEvents","hrtimeToEpochNanoseconds","initializeTraceState","recordTraceEvents","trace","NUM_OF_MICROSEC_IN_NANOSEC","BigInt","NUM_OF_MILLISEC_IN_NANOSEC","count","getId","defaultParentSpanId","shouldSaveTraceEvents","savedTraceEvents","RECORD_SPAN_THRESHOLD_MS","parseInt","process","env","NEXT_TRACE_SPAN_THRESHOLD_MS","constructor","name","parentId","attrs","startTime","wallStartTimeMs","status","id","_start","hrtime","bigint","now","Date","stop","stopTime","end","duration","Number","MAX_SAFE_INTEGER","Error","timestamp","traceEvent","tags","reporter","report","push","traceChild","manualTraceChild","correction","span","undefined","setAttribute","key","value","traceFn","fn","e","traceAsyncFn","flushAll","close","lastId","state","events","hrtimeValue","offset"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;IA6BaA,IAAI;eAAJA;;IATDC,UAAU;eAAVA;;IA+LCC,gBAAgB;eAAhBA;;IAhCAC,cAAc;eAAdA;;IAKAC,gBAAgB;eAAhBA;;IAXAC,cAAc;eAAdA;;IAsBGC,cAAc;eAAdA;;IA2BAC,wBAAwB;eAAxBA;;IAjCHC,oBAAoB;eAApBA;;IAUGC,iBAAiB;eAAjBA;;IAlCHC,KAAK;eAALA;;;wBArKY;AAGzB,MAAMC,6BAA6BC,OAAO;AAC1C,MAAMC,6BAA6BD,OAAO;AAE1C,IAAIE,QAAQ;AACZ,MAAMC,QAAQ;IACZD;IACA,OAAOA;AACT;AACA,IAAIE;AACJ,IAAIC;AACJ,IAAIC,mBAAiC,EAAE;AAEvC,MAAMC,2BAA2BC,SAC/BC,QAAQC,GAAG,CAACC,4BAA4B,IAAI;AAIvC,IAAA,AAAKtB,oCAAAA;;;WAAAA;;AASL,MAAMD;IAWXwB,YAAY,EACVC,IAAI,EACJC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,eAAe,EAShB,CAAE;QACD,IAAI,CAACJ,IAAI,GAAGA;QACZ,IAAI,CAACC,QAAQ,GAAGA,YAAYV;QAC5B,IAAI,CAACW,KAAK,GAAGA,QAAQ;YAAE,GAAGA,KAAK;QAAC,IAAI,CAAC;QAErC,IAAI,CAACG,MAAM;QACX,IAAI,CAACC,EAAE,GAAGhB;QACV,IAAI,CAACiB,MAAM,GAAGJ,aAAaP,QAAQY,MAAM,CAACC,MAAM;QAChD,wEAAwE;QACxE,iDAAiD;QACjD,2IAA2I;QAC3I,wDAAwD;QACxD,iFAAiF;QACjF,IAAI,CAACC,GAAG,GAAGN,mBAAmBO,KAAKD,GAAG;IACxC;IAEA,yEAAyE;IACzE,+DAA+D;IAC/D,wEAAwE;IACxE,yCAAyC;IACzCE,KAAKC,QAAiB,EAAE;QACtB,IAAI,IAAI,CAACR,MAAM,gBAAyB;YACtC,oCAAoC;YACpC,yFAAyF;YACzF;QACF;QACA,MAAMS,MAAcD,YAAYjB,QAAQY,MAAM,CAACC,MAAM;QACrD,MAAMM,WAAW,AAACD,CAAAA,MAAM,IAAI,CAACP,MAAM,AAAD,IAAKrB;QACvC,IAAI,CAACmB,MAAM;QACX,IAAIU,WAAWC,OAAOC,gBAAgB,EAAE;YACtC,MAAM,IAAIC,MAAM,CAAC,4CAA4C,EAAEH,UAAU;QAC3E;QACA,MAAMI,YAAY,IAAI,CAACZ,MAAM,GAAGrB;QAChC,MAAMkC,aAAyB;YAC7BpB,MAAM,IAAI,CAACA,IAAI;YACfe,UAAUC,OAAOD;YACjBI,WAAWH,OAAOG;YAClBb,IAAI,IAAI,CAACA,EAAE;YACXL,UAAU,IAAI,CAACA,QAAQ;YACvBoB,MAAM,IAAI,CAACnB,KAAK;YAChBC,WAAW,IAAI,CAACO,GAAG;QACrB;QACA,IAAIK,WAAWrB,2BAA2B,MAAM;YAC9C4B,gBAAQ,CAACC,MAAM,CAACH;YAChB,IAAI5B,uBAAuB;gBACzBC,iBAAiB+B,IAAI,CAACJ;YACxB;QACF;IACF;IAEAK,WAAWzB,IAAY,EAAEE,KAAkB,EAAE;QAC3C,OAAO,IAAI3B,KAAK;YAAEyB;YAAMC,UAAU,IAAI,CAACK,EAAE;YAAEJ;QAAM;IACnD;IAEAwB,iBACE1B,IAAY,EACZ,yCAAyC;IACzCG,SAAkB,EAClB,wCAAwC;IACxCU,QAAiB,EACjBX,KAAkB,EAClB;QACA,0FAA0F;QAC1F,MAAMyB,aACJ/B,QAAQY,MAAM,CAACC,MAAM,KAAKtB,OAAOwB,KAAKD,GAAG,MAAMtB;QACjD,MAAMwC,OAAO,IAAIrD,KAAK;YACpByB;YACAC,UAAU,IAAI,CAACK,EAAE;YACjBJ;YACAC,WAAWA,YAAYA,YAAYwB,aAAa/B,QAAQY,MAAM,CAACC,MAAM;YACrE,wEAAwE;YACxE,iEAAiE;YACjE,wEAAwE;YACxEL,iBAAiBD,YACba,OAAOb,YAAYf,8BACnByC;QACN;QACAD,KAAKhB,IAAI,CAACC,WAAWA,WAAWc,aAAa/B,QAAQY,MAAM,CAACC,MAAM;IACpE;IAEAnB,QAAQ;QACN,OAAO,IAAI,CAACgB,EAAE;IAChB;IAEAwB,aAAaC,GAAW,EAAEC,KAAc,EAAE;QACxC,IAAI,CAAC9B,KAAK,CAAC6B,IAAI,GAAGC;IACpB;IAEAC,QAAWC,EAAqB,EAAK;QACnC,IAAI;YACF,OAAOA,GAAG,IAAI;QAChB,EAAE,OAAOC,GAAG;YACV,IAAI,CAACjC,KAAK,CAAC,SAAS,GAAG;YACvB,MAAMiC;QACR,SAAU;YACR,IAAI,CAACvB,IAAI;QACX;IACF;IAEA,MAAMwB,aAAgBF,EAAkC,EAAc;QACpE,IAAI;YACF,OAAO,MAAMA,GAAG,IAAI;QACtB,EAAE,OAAOC,GAAG;YACV,IAAI,CAACjC,KAAK,CAAC,SAAS,GAAG;YACvB,MAAMiC;QACR,SAAU;YACR,IAAI,CAACvB,IAAI;QACX;IACF;AACF;AAEO,MAAM3B,QAAQ,CACnBe,MACAC,UACAC;IAEA,OAAO,IAAI3B,KAAK;QAAEyB;QAAMC;QAAUC;IAAM;AAC1C;AAEO,MAAMtB,iBAAiB,IAAM0C,gBAAQ,CAACe,QAAQ;AAM9C,MAAM3D,iBAAiB,IAAM4C,gBAAQ,CAACgB,KAAK;AAK3C,MAAM3D,mBAAmB,IAAmB,CAAA;QACjDY;QACAgD,QAAQlD;QACRG;IACF,CAAA;AACO,MAAMT,uBAAuB,CAACyD;IACnCnD,QAAQmD,MAAMD,MAAM;IACpBhD,sBAAsBiD,MAAMjD,mBAAmB;IAC/CC,wBAAwBgD,MAAMhD,qBAAqB;AACrD;AAEO,SAASX;IACd,OAAOY;AACT;AAEO,SAAST,kBAAkByD,MAAoB;IACpD,KAAK,MAAMrB,cAAcqB,OAAQ;QAC/BnB,gBAAQ,CAACC,MAAM,CAACH;QAChB,IAAIA,WAAWd,EAAE,GAAGjB,OAAO;YACzBA,QAAQ+B,WAAWd,EAAE,GAAG;QAC1B;IACF;IACA,IAAId,uBAAuB;QACzBC,iBAAiB+B,IAAI,IAAIiB;IAC3B;AACF;AAEO,MAAMhE,mBAAmB,IAAOgB,mBAAmB,EAAE;AAWrD,SAASX,yBAAyB4D,WAAmB;IAC1D,MAAMC,SACJxD,OAAOwB,KAAKD,GAAG,MAAMtB,6BAA6BQ,QAAQY,MAAM,CAACC,MAAM;IACzE,OAAOiC,cAAcC;AACvB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/trace.test.js b/e-commerce/node_modules/next/dist/trace/trace.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e0d94d91d8474c9b94132e9876bd3d1268b017ed --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace.test.js @@ -0,0 +1,520 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _promises = require("fs/promises"); +const _fs = /*#__PURE__*/ _interop_require_wildcard(require("fs")); +const _path = require("path"); +const _os = require("os"); +const _constants = require("../shared/lib/constants"); +const _tojson = require("./report/to-json"); +const _shared = require("./shared"); +const _trace = require("./trace"); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function traceEvent(name) { + return { + name, + duration: 1, + timestamp: 1, + id: 1, + startTime: 1, + tags: {} + }; +} +// Newline-delimited JSON: each line is an array of spans, as read by +// `test/lib/parse-trace-file.ts` and `trace-uploader.ts`. +function readSpans(file) { + return (0, _fs.readFileSync)(file, 'utf-8').split('\n').filter(Boolean).flatMap((line)=>JSON.parse(line)); +} +function readSpanNames(file) { + return readSpans(file).map((event)=>event.name); +} +describe('Trace', ()=>{ + const tmpDirs = []; + async function makeTmpDir() { + const dir = await (0, _promises.mkdtemp)((0, _path.join)((0, _os.tmpdir)(), 'json-reporter')); + tmpDirs.push(dir); + return dir; + } + // Reporters created by a test hold a descriptor on their trace file until + // closed. `closeAllTraces` only reaches the global reporter, so these have + // to be tracked separately or cleanup cannot remove their directory. + const reporters = []; + function makeJsonReporter(...args) { + const reporter = (0, _tojson.createJsonReporter)(...args); + reporters.push(reporter); + return reporter; + } + beforeEach(()=>{ + (0, _trace.initializeTraceState)({ + lastId: 0, + shouldSaveTraceEvents: true + }); + (0, _trace.clearTraceEvents)(); + // `traceGlobals` outlives each test, so reset what these tests set. + (0, _shared.setGlobal)('distDir', undefined); + (0, _shared.setGlobal)('phase', undefined); + }); + afterAll(async ()=>{ + // Windows refuses to remove a directory containing an open file, so every + // trace file handle has to go first -- the global reporter's and the ones + // the tests created themselves. + (0, _trace.closeAllTraces)(); + for (const reporter of reporters.splice(0)){ + reporter.close == null ? void 0 : reporter.close.call(reporter); + } + await Promise.all(tmpDirs.splice(0).map((dir)=>(0, _promises.rm)(dir, { + recursive: true, + force: true + }))); + }); + describe('Tracer', ()=>{ + it('traces a block of code', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', 'anything'); + const root = (0, _trace.trace)('root-span', undefined, { + 'some-tag': 'some-value' + }); + root.traceChild('child-span').traceFn(()=>null); + await root.traceChild('async-child-span').traceAsyncFn(async ()=>{ + const delayedPromise = new Promise((resolve)=>{ + setTimeout(resolve, 100); + }); + await delayedPromise; + }); + root.stop(); + const traceEvents = (0, _trace.getTraceEvents)(); + expect(traceEvents.length).toEqual(3); + expect(traceEvents[0].name).toEqual('child-span'); + expect(traceEvents[1].name).toEqual('async-child-span'); + expect(traceEvents[2].name).toEqual('root-span'); + // Check that the serialized .next/trace file looks correct. + (0, _trace.flushAllTraces)(); + const serializedTraces = readSpans((0, _path.join)(tmpDir, 'trace')); + expect(serializedTraces).toMatchObject([ + { + id: 2, + name: 'child-span', + parentId: 1, + startTime: expect.any(Number), + timestamp: expect.any(Number), + duration: expect.any(Number), + tags: {} + }, + { + id: 3, + name: 'async-child-span', + parentId: 1, + startTime: expect.any(Number), + timestamp: expect.any(Number), + duration: expect.any(Number), + tags: {} + }, + { + id: 1, + name: 'root-span', + startTime: expect.any(Number), + timestamp: expect.any(Number), + duration: expect.any(Number), + tags: { + 'some-tag': 'some-value' + } + } + ]); + }); + it('records manualTraceChild spans with their own start time', ()=>{ + const root = (0, _trace.trace)('root-span'); + // A span that started one minute ago and ran for 1.5s, as happens when + // the event is only recorded after the work completes (e.g. Turbopack + // compilation events forwarded from Rust). + const startMs = Date.now() - 60000; + const stopMs = startMs + 1500; + const msToNs = (ms)=>BigInt(ms) * BigInt(1000000); + root.manualTraceChild('manual-child', msToNs(startMs), msToNs(stopMs)); + root.stop(); + const events = (0, _trace.getTraceEvents)(); + const child = events.find((e)=>e.name === 'manual-child'); + expect(child).toBeDefined(); + // startTime must be the span's actual start, not the time the event was + // recorded (which is when manualTraceChild is called). + expect(child.startTime).toEqual(startMs); + expect(child.duration).toEqual(1500000); + }); + // Builds flush repeatedly -- after each compilation, and again at the + // end -- so every flush must leave the file usable. + it('writes buffered spans on each flush', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + const reporter = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + const file = (0, _path.join)(tmpDir, 'trace'); + reporter.report(traceEvent('first')); + reporter.flushAll(); + expect(readSpanNames(file)).toEqual([ + 'first' + ]); + // A flush with nothing buffered is harmless. + reporter.report(traceEvent('second')); + reporter.flushAll(); + reporter.flushAll(); + expect(readSpanNames(file)).toEqual([ + 'first', + 'second' + ]); + }); + // The dev server records spans before it cleans its dist dir. Holding a + // descriptor across that clean would leave it pointing at an unlinked + // inode -- writes still succeed, so the trace silently never appears on + // disk. Staying closed until there is something to write avoids it. + it('does not touch the filesystem until the first flush', async ()=>{ + const tmpDir = await makeTmpDir(); + const distDir = (0, _path.join)(tmpDir, 'dist'); + (0, _shared.setGlobal)('distDir', distDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_DEVELOPMENT_SERVER); + const reporter = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + reporter.report(traceEvent('buffered')); + // Buffered only: neither the dist dir nor the file exists yet, so a + // clean at this point has nothing to unlink. + expect(_fs.default.existsSync(distDir)).toBe(false); + reporter.flushAll(); + expect(readSpanNames((0, _path.join)(distDir, 'trace'))).toEqual([ + 'buffered' + ]); + }); + it('flushes on its own once the buffer fills', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + const reporter = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + const file = (0, _path.join)(tmpDir, 'trace'); + // Each event encodes to ~100 bytes, so this far exceeds the buffer. + for(let i = 0; i < 2000; i++){ + reporter.report(traceEvent(`span-${i}`)); + } + expect(readSpanNames(file).length).toBeGreaterThan(0); + reporter.flushAll(); + expect(readSpanNames(file).length).toBe(2000); + }); + it('truncates in production but appends in development', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + const file = (0, _path.join)(tmpDir, 'trace'); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + const build = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + build.report(traceEvent('from-build')); + build.flushAll(); + expect(readSpanNames(file)).toEqual([ + 'from-build' + ]); + // A second production reporter starts the file over. + const rebuild = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + rebuild.report(traceEvent('from-rebuild')); + rebuild.flushAll(); + expect(readSpanNames(file)).toEqual([ + 'from-rebuild' + ]); + // Dev keeps accumulating across sessions instead. + (0, _shared.setGlobal)('phase', _constants.PHASE_DEVELOPMENT_SERVER); + const dev = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + dev.report(traceEvent('from-dev')); + dev.flushAll(); + expect(readSpanNames(file)).toEqual([ + 'from-rebuild', + 'from-dev' + ]); + }); + // The limit is counted in UTF-8 bytes: counting UTF-16 code units instead + // lets a non-ASCII trace reach ~3x the configured cap. + it('starts the file over once it exceeds the size limit', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + const file = (0, _path.join)(tmpDir, 'trace'); + // 200 CJK characters: 200 code units, but 600 UTF-8 bytes, so a limit + // of 1024 fits one of these lines and not two. + const first = '第'.repeat(200); + const second = '弐'.repeat(200); + const limit = 1024; + const reporter = makeJsonReporter({ + filename: 'trace', + sizeLimit: limit + }); + reporter.report(traceEvent(first)); + reporter.flushAll(); + expect(readSpanNames(file)).toEqual([ + first + ]); + reporter.report(traceEvent(second)); + reporter.flushAll(); + expect(readSpanNames(file)).toEqual([ + second + ]); + expect(Buffer.byteLength((0, _fs.readFileSync)(file, 'utf-8'), 'utf8')).toBeLessThanOrEqual(limit); + }); + // A truncated batch fails quietly: the last line has no newline, so + // readers skip it and those spans simply vanish. + it('writes complete batches at every buffer boundary', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + // Equal-sized events tile the buffer, so each length puts a batch + // boundary at a different offset. Sweeping rather than picking one + // length because the encoded size shifts with `traceId` ($TRACE_ID). + // 200 events of any of these sizes overflows the buffer several times. + for(let length = 100; length < 260; length++){ + const reporter = makeJsonReporter({ + filename: `trace-${length}`, + sizeLimit: Infinity + }); + const names = []; + for(let i = 0; i < 200; i++){ + const name = 'n'.repeat(length); + names.push(name); + reporter.report(traceEvent(name)); + } + reporter.flushAll(); + const written = (0, _path.join)(tmpDir, `trace-${length}`); + expect((0, _fs.readFileSync)(written, 'utf-8').endsWith(']\n')).toBe(true); + expect(readSpanNames(written)).toEqual(names); + } + }); + it('writes an event too large to buffer', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + const reporter = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + const file = (0, _path.join)(tmpDir, 'trace'); + // Far larger than the buffer. + const huge = 'x'.repeat(100 * 1024); + reporter.report(traceEvent('before-huge')); + reporter.report(traceEvent(huge)); + reporter.report(traceEvent('after-huge')); + reporter.flushAll(); + expect(readSpanNames(file)).toEqual([ + 'before-huge', + huge, + 'after-huge' + ]); + }); + // `Buffer.write` stops at the last whole character, so an event that + // overruns the buffer reports a count short of the capacity. Treating + // that as complete stores a JSON string with no closing quote, which + // breaks the whole line. + it('never stores a partially encoded multi-byte event', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + // Sweep name lengths so events land at every offset relative to the + // buffer boundary, mixing 1-, 3- and 4-byte characters. + for(let length = 1; length < 120; length++){ + const reporter = makeJsonReporter({ + filename: `trace-${length}`, + sizeLimit: Infinity + }); + const names = []; + for(let i = 0; i < 400; i++){ + const name = `${'第'.repeat(length)}😀${'a'.repeat(i % 7)}`; + names.push(name); + reporter.report(traceEvent(name)); + } + reporter.flushAll(); + expect(readSpanNames((0, _path.join)(tmpDir, `trace-${length}`))).toEqual(names); + } + }); + // Tracing is diagnostic: a full disk should cost spans, not the build. + it('keeps tracing when a write fails', async ()=>{ + const tmpDir = await makeTmpDir(); + (0, _shared.setGlobal)('distDir', tmpDir); + (0, _shared.setGlobal)('phase', _constants.PHASE_PRODUCTION_BUILD); + const reporter = makeJsonReporter({ + filename: 'trace', + sizeLimit: Infinity + }); + const file = (0, _path.join)(tmpDir, 'trace'); + reporter.report(traceEvent('before-failure')); + reporter.flushAll(); + const writeSync = jest.spyOn(_fs.default, 'writeSync').mockImplementation(()=>{ + throw Object.assign(new Error('ENOSPC'), { + code: 'ENOSPC' + }); + }); + const consoleLog = jest.spyOn(console, 'log').mockImplementation(()=>{}); + try { + reporter.report(traceEvent('during-failure')); + expect(()=>reporter.flushAll()).not.toThrow(); + expect(consoleLog).toHaveBeenCalled(); + } finally{ + consoleLog.mockRestore(); + writeSync.mockRestore(); + } + reporter.report(traceEvent('after-failure')); + reporter.flushAll(); + expect(readSpanNames(file)).toEqual([ + 'before-failure', + 'after-failure' + ]); + }); + }); + describe('Worker', ()=>{ + it('exports and initializes trace state', ()=>{ + const root = (0, _trace.trace)('root-span'); + expect(root.getId()).toEqual(1); + const traceState = (0, _trace.exportTraceState)(); + expect(traceState.lastId).toEqual(1); + (0, _trace.initializeTraceState)({ + lastId: 101 + }); + const span = (0, _trace.trace)('another-span'); + expect(span.getId()).toEqual(102); + }); + it('trace data is serializable to a worker', async ()=>{ + const root = (0, _trace.trace)('root-span'); + root.traceChild('child-span').traceFn(()=>null); + root.stop(); + const traceEvents = (0, _trace.getTraceEvents)(); + expect(traceEvents.length).toEqual(2); + // This is a proxy check to make sure the object would be serializable + // to a worker. It will fail if the data contains some unserializable + // objects like BigInt. + const clone = JSON.parse(JSON.stringify(traceEvents)); + expect(clone).toEqual(traceEvents); + }); + it('correctly reports trace data from multiple workers', ()=>{ + // This test simulates workers creating traces and propagating them + // back to the main process for recording. It doesn't use + // actual workers since they are more difficult to set up in tests. + (0, _trace.initializeTraceState)({ + lastId: 5, + defaultParentSpanId: 1, + shouldSaveTraceEvents: true + }); + const worker1Span = (0, _trace.trace)('worker1'); + worker1Span.traceChild('webpack-compilation1').traceFn(()=>null); + worker1Span.stop(); + const worker1Traces = (0, _trace.getTraceEvents)(); + expect(worker1Traces.length).toEqual(2); + // Repeat for a second worker. + (0, _trace.clearTraceEvents)(); + (0, _trace.initializeTraceState)({ + lastId: 10, + defaultParentSpanId: 1, + shouldSaveTraceEvents: true + }); + const worker2Span = (0, _trace.trace)('worker2'); + worker2Span.traceChild('webpack-compilation2').traceFn(()=>null); + worker2Span.stop(); + const worker2Traces = (0, _trace.getTraceEvents)(); + expect(worker2Traces.length).toEqual(2); + // Now simulate the traces in the main process and record the traces + // from each worker. + (0, _trace.clearTraceEvents)(); + (0, _trace.initializeTraceState)({ + lastId: 0, + shouldSaveTraceEvents: true + }); + const root = (0, _trace.trace)('next-build'); + root.traceChild('some-child-span').traceFn(()=>null); + (0, _trace.recordTraceEvents)(worker1Traces); + expect((0, _trace.exportTraceState)().lastId).toEqual(8); + (0, _trace.recordTraceEvents)(worker2Traces); + expect((0, _trace.exportTraceState)().lastId).toEqual(13); + root.traceChild('another-child-span').traceFn(()=>null); + root.stop(); + // Check that the final output looks correct. + const allTraces = (0, _trace.getTraceEvents)(); + expect(allTraces.length).toEqual(7); + const firstSpan = allTraces[0]; + expect(firstSpan.name).toEqual('some-child-span'); + expect(firstSpan.id).toEqual(2); + expect(firstSpan.parentId).toEqual(1); + const worker1Child = allTraces[1]; + expect(worker1Child.name).toEqual('webpack-compilation1'); + expect(worker1Child.id).toEqual(7); + expect(worker1Child.parentId).toEqual(6); + const worker1Root = allTraces[2]; + expect(worker1Root.name).toEqual('worker1'); + expect(worker1Root.id).toEqual(6); + expect(worker1Root.parentId).toEqual(1); + const worker2Child = allTraces[3]; + expect(worker2Child.name).toEqual('webpack-compilation2'); + expect(worker2Child.id).toEqual(12); + expect(worker2Child.parentId).toEqual(11); + const worker2Root = allTraces[4]; + expect(worker2Root.name).toEqual('worker2'); + expect(worker2Root.id).toEqual(11); + expect(worker2Root.parentId).toEqual(1); + const lastChildSpan = allTraces[5]; + expect(lastChildSpan.name).toEqual('another-child-span'); + expect(lastChildSpan.id).toEqual(14); + expect(lastChildSpan.parentId).toEqual(1); + const rootSpan = allTraces[6]; + expect(rootSpan.name).toEqual('next-build'); + expect(rootSpan.id).toEqual(1); + expect(rootSpan.parentId).toBeUndefined(); + }); + }); +}); + +//# sourceMappingURL=trace.test.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/trace.test.js.map b/e-commerce/node_modules/next/dist/trace/trace.test.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7a8a278b0580b71b121be9a342ba31101654e599 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/trace.test.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/trace/trace.test.ts"],"sourcesContent":["import { mkdtemp, rm } from 'fs/promises'\nimport fs, { readFileSync } from 'fs'\nimport { join } from 'path'\nimport { tmpdir } from 'os'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PHASE_PRODUCTION_BUILD,\n} from '../shared/lib/constants'\nimport { createJsonReporter } from './report/to-json'\nimport type { Reporter } from './report/types'\nimport type { TraceEvent } from './types'\nimport { setGlobal } from './shared'\nimport {\n clearTraceEvents,\n closeAllTraces,\n exportTraceState,\n flushAllTraces,\n getTraceEvents,\n initializeTraceState,\n recordTraceEvents,\n trace,\n} from './trace'\n\nfunction traceEvent(name: string): TraceEvent {\n return {\n name,\n duration: 1,\n timestamp: 1,\n id: 1,\n startTime: 1,\n tags: {},\n }\n}\n\n// Newline-delimited JSON: each line is an array of spans, as read by\n// `test/lib/parse-trace-file.ts` and `trace-uploader.ts`.\nfunction readSpans(file: string): TraceEvent[] {\n return readFileSync(file, 'utf-8')\n .split('\\n')\n .filter(Boolean)\n .flatMap((line) => JSON.parse(line) as TraceEvent[])\n}\n\nfunction readSpanNames(file: string): string[] {\n return readSpans(file).map((event) => event.name)\n}\n\ndescribe('Trace', () => {\n const tmpDirs: string[] = []\n async function makeTmpDir() {\n const dir = await mkdtemp(join(tmpdir(), 'json-reporter'))\n tmpDirs.push(dir)\n return dir\n }\n\n // Reporters created by a test hold a descriptor on their trace file until\n // closed. `closeAllTraces` only reaches the global reporter, so these have\n // to be tracked separately or cleanup cannot remove their directory.\n const reporters: Reporter[] = []\n function makeJsonReporter(\n ...args: Parameters\n ): Reporter {\n const reporter = createJsonReporter(...args)\n reporters.push(reporter)\n return reporter\n }\n\n beforeEach(() => {\n initializeTraceState({\n lastId: 0,\n shouldSaveTraceEvents: true,\n })\n clearTraceEvents()\n // `traceGlobals` outlives each test, so reset what these tests set.\n setGlobal('distDir', undefined)\n setGlobal('phase', undefined)\n })\n\n afterAll(async () => {\n // Windows refuses to remove a directory containing an open file, so every\n // trace file handle has to go first -- the global reporter's and the ones\n // the tests created themselves.\n closeAllTraces()\n for (const reporter of reporters.splice(0)) {\n reporter.close?.()\n }\n await Promise.all(\n tmpDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))\n )\n })\n\n describe('Tracer', () => {\n it('traces a block of code', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', 'anything')\n\n const root = trace('root-span', undefined, {\n 'some-tag': 'some-value',\n })\n root.traceChild('child-span').traceFn(() => null)\n await root.traceChild('async-child-span').traceAsyncFn(async () => {\n const delayedPromise = new Promise((resolve) => {\n setTimeout(resolve, 100)\n })\n await delayedPromise\n })\n root.stop()\n const traceEvents = getTraceEvents()\n expect(traceEvents.length).toEqual(3)\n expect(traceEvents[0].name).toEqual('child-span')\n expect(traceEvents[1].name).toEqual('async-child-span')\n expect(traceEvents[2].name).toEqual('root-span')\n\n // Check that the serialized .next/trace file looks correct.\n flushAllTraces()\n const serializedTraces = readSpans(join(tmpDir, 'trace'))\n expect(serializedTraces).toMatchObject([\n {\n id: 2,\n name: 'child-span',\n parentId: 1,\n startTime: expect.any(Number),\n timestamp: expect.any(Number),\n duration: expect.any(Number),\n tags: {},\n },\n {\n id: 3,\n name: 'async-child-span',\n parentId: 1,\n startTime: expect.any(Number),\n timestamp: expect.any(Number),\n duration: expect.any(Number),\n tags: {},\n },\n {\n id: 1,\n name: 'root-span',\n startTime: expect.any(Number),\n timestamp: expect.any(Number),\n duration: expect.any(Number),\n tags: {\n 'some-tag': 'some-value',\n },\n },\n ])\n })\n\n it('records manualTraceChild spans with their own start time', () => {\n const root = trace('root-span')\n // A span that started one minute ago and ran for 1.5s, as happens when\n // the event is only recorded after the work completes (e.g. Turbopack\n // compilation events forwarded from Rust).\n const startMs = Date.now() - 60_000\n const stopMs = startMs + 1500\n const msToNs = (ms: number) => BigInt(ms) * BigInt(1_000_000)\n root.manualTraceChild('manual-child', msToNs(startMs), msToNs(stopMs))\n root.stop()\n\n const events = getTraceEvents()\n const child = events.find((e) => e.name === 'manual-child')\n expect(child).toBeDefined()\n // startTime must be the span's actual start, not the time the event was\n // recorded (which is when manualTraceChild is called).\n expect(child!.startTime).toEqual(startMs)\n expect(child!.duration).toEqual(1_500_000)\n })\n\n // Builds flush repeatedly -- after each compilation, and again at the\n // end -- so every flush must leave the file usable.\n it('writes buffered spans on each flush', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n const reporter = makeJsonReporter({\n filename: 'trace',\n sizeLimit: Infinity,\n })\n const file = join(tmpDir, 'trace')\n\n reporter.report(traceEvent('first'))\n reporter.flushAll()\n expect(readSpanNames(file)).toEqual(['first'])\n\n // A flush with nothing buffered is harmless.\n reporter.report(traceEvent('second'))\n reporter.flushAll()\n reporter.flushAll()\n expect(readSpanNames(file)).toEqual(['first', 'second'])\n })\n\n // The dev server records spans before it cleans its dist dir. Holding a\n // descriptor across that clean would leave it pointing at an unlinked\n // inode -- writes still succeed, so the trace silently never appears on\n // disk. Staying closed until there is something to write avoids it.\n it('does not touch the filesystem until the first flush', async () => {\n const tmpDir = await makeTmpDir()\n const distDir = join(tmpDir, 'dist')\n setGlobal('distDir', distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n const reporter = makeJsonReporter({\n filename: 'trace',\n sizeLimit: Infinity,\n })\n\n reporter.report(traceEvent('buffered'))\n // Buffered only: neither the dist dir nor the file exists yet, so a\n // clean at this point has nothing to unlink.\n expect(fs.existsSync(distDir)).toBe(false)\n\n reporter.flushAll()\n expect(readSpanNames(join(distDir, 'trace'))).toEqual(['buffered'])\n })\n\n it('flushes on its own once the buffer fills', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n const reporter = makeJsonReporter({\n filename: 'trace',\n sizeLimit: Infinity,\n })\n const file = join(tmpDir, 'trace')\n\n // Each event encodes to ~100 bytes, so this far exceeds the buffer.\n for (let i = 0; i < 2000; i++) {\n reporter.report(traceEvent(`span-${i}`))\n }\n expect(readSpanNames(file).length).toBeGreaterThan(0)\n\n reporter.flushAll()\n expect(readSpanNames(file).length).toBe(2000)\n })\n\n it('truncates in production but appends in development', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n const file = join(tmpDir, 'trace')\n\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n const build = makeJsonReporter({\n filename: 'trace',\n sizeLimit: Infinity,\n })\n build.report(traceEvent('from-build'))\n build.flushAll()\n expect(readSpanNames(file)).toEqual(['from-build'])\n\n // A second production reporter starts the file over.\n const rebuild = makeJsonReporter({\n filename: 'trace',\n sizeLimit: Infinity,\n })\n rebuild.report(traceEvent('from-rebuild'))\n rebuild.flushAll()\n expect(readSpanNames(file)).toEqual(['from-rebuild'])\n\n // Dev keeps accumulating across sessions instead.\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n const dev = makeJsonReporter({ filename: 'trace', sizeLimit: Infinity })\n dev.report(traceEvent('from-dev'))\n dev.flushAll()\n expect(readSpanNames(file)).toEqual(['from-rebuild', 'from-dev'])\n })\n\n // The limit is counted in UTF-8 bytes: counting UTF-16 code units instead\n // lets a non-ASCII trace reach ~3x the configured cap.\n it('starts the file over once it exceeds the size limit', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n const file = join(tmpDir, 'trace')\n\n // 200 CJK characters: 200 code units, but 600 UTF-8 bytes, so a limit\n // of 1024 fits one of these lines and not two.\n const first = '第'.repeat(200)\n const second = '弐'.repeat(200)\n const limit = 1024\n const reporter = makeJsonReporter({\n filename: 'trace',\n sizeLimit: limit,\n })\n\n reporter.report(traceEvent(first))\n reporter.flushAll()\n expect(readSpanNames(file)).toEqual([first])\n\n reporter.report(traceEvent(second))\n reporter.flushAll()\n expect(readSpanNames(file)).toEqual([second])\n expect(\n Buffer.byteLength(readFileSync(file, 'utf-8'), 'utf8')\n ).toBeLessThanOrEqual(limit)\n })\n\n // A truncated batch fails quietly: the last line has no newline, so\n // readers skip it and those spans simply vanish.\n it('writes complete batches at every buffer boundary', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n\n // Equal-sized events tile the buffer, so each length puts a batch\n // boundary at a different offset. Sweeping rather than picking one\n // length because the encoded size shifts with `traceId` ($TRACE_ID).\n // 200 events of any of these sizes overflows the buffer several times.\n for (let length = 100; length < 260; length++) {\n const reporter = makeJsonReporter({\n filename: `trace-${length}`,\n sizeLimit: Infinity,\n })\n const names: string[] = []\n for (let i = 0; i < 200; i++) {\n const name = 'n'.repeat(length)\n names.push(name)\n reporter.report(traceEvent(name))\n }\n reporter.flushAll()\n\n const written = join(tmpDir, `trace-${length}`)\n expect(readFileSync(written, 'utf-8').endsWith(']\\n')).toBe(true)\n expect(readSpanNames(written)).toEqual(names)\n }\n })\n\n it('writes an event too large to buffer', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n const reporter = makeJsonReporter({\n filename: 'trace',\n sizeLimit: Infinity,\n })\n const file = join(tmpDir, 'trace')\n\n // Far larger than the buffer.\n const huge = 'x'.repeat(100 * 1024)\n reporter.report(traceEvent('before-huge'))\n reporter.report(traceEvent(huge))\n reporter.report(traceEvent('after-huge'))\n reporter.flushAll()\n\n expect(readSpanNames(file)).toEqual(['before-huge', huge, 'after-huge'])\n })\n\n // `Buffer.write` stops at the last whole character, so an event that\n // overruns the buffer reports a count short of the capacity. Treating\n // that as complete stores a JSON string with no closing quote, which\n // breaks the whole line.\n it('never stores a partially encoded multi-byte event', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n\n // Sweep name lengths so events land at every offset relative to the\n // buffer boundary, mixing 1-, 3- and 4-byte characters.\n for (let length = 1; length < 120; length++) {\n const reporter = makeJsonReporter({\n filename: `trace-${length}`,\n sizeLimit: Infinity,\n })\n const names: string[] = []\n for (let i = 0; i < 400; i++) {\n const name = `${'第'.repeat(length)}😀${'a'.repeat(i % 7)}`\n names.push(name)\n reporter.report(traceEvent(name))\n }\n reporter.flushAll()\n\n expect(readSpanNames(join(tmpDir, `trace-${length}`))).toEqual(names)\n }\n })\n\n // Tracing is diagnostic: a full disk should cost spans, not the build.\n it('keeps tracing when a write fails', async () => {\n const tmpDir = await makeTmpDir()\n setGlobal('distDir', tmpDir)\n setGlobal('phase', PHASE_PRODUCTION_BUILD)\n const reporter = makeJsonReporter({\n filename: 'trace',\n sizeLimit: Infinity,\n })\n const file = join(tmpDir, 'trace')\n\n reporter.report(traceEvent('before-failure'))\n reporter.flushAll()\n\n const writeSync = jest.spyOn(fs, 'writeSync').mockImplementation(() => {\n throw Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' })\n })\n const consoleLog = jest.spyOn(console, 'log').mockImplementation(() => {})\n try {\n reporter.report(traceEvent('during-failure'))\n expect(() => reporter.flushAll()).not.toThrow()\n expect(consoleLog).toHaveBeenCalled()\n } finally {\n consoleLog.mockRestore()\n writeSync.mockRestore()\n }\n\n reporter.report(traceEvent('after-failure'))\n reporter.flushAll()\n expect(readSpanNames(file)).toEqual(['before-failure', 'after-failure'])\n })\n })\n\n describe('Worker', () => {\n it('exports and initializes trace state', () => {\n const root = trace('root-span')\n expect(root.getId()).toEqual(1)\n const traceState = exportTraceState()\n expect(traceState.lastId).toEqual(1)\n initializeTraceState({\n lastId: 101,\n })\n const span = trace('another-span')\n expect(span.getId()).toEqual(102)\n })\n\n it('trace data is serializable to a worker', async () => {\n const root = trace('root-span')\n root.traceChild('child-span').traceFn(() => null)\n root.stop()\n const traceEvents = getTraceEvents()\n expect(traceEvents.length).toEqual(2)\n // This is a proxy check to make sure the object would be serializable\n // to a worker. It will fail if the data contains some unserializable\n // objects like BigInt.\n const clone = JSON.parse(JSON.stringify(traceEvents))\n expect(clone).toEqual(traceEvents)\n })\n\n it('correctly reports trace data from multiple workers', () => {\n // This test simulates workers creating traces and propagating them\n // back to the main process for recording. It doesn't use\n // actual workers since they are more difficult to set up in tests.\n initializeTraceState({\n lastId: 5,\n defaultParentSpanId: 1,\n shouldSaveTraceEvents: true,\n })\n const worker1Span = trace('worker1')\n worker1Span.traceChild('webpack-compilation1').traceFn(() => null)\n worker1Span.stop()\n const worker1Traces = getTraceEvents()\n expect(worker1Traces.length).toEqual(2)\n\n // Repeat for a second worker.\n clearTraceEvents()\n initializeTraceState({\n lastId: 10,\n defaultParentSpanId: 1,\n shouldSaveTraceEvents: true,\n })\n const worker2Span = trace('worker2')\n worker2Span.traceChild('webpack-compilation2').traceFn(() => null)\n worker2Span.stop()\n const worker2Traces = getTraceEvents()\n expect(worker2Traces.length).toEqual(2)\n\n // Now simulate the traces in the main process and record the traces\n // from each worker.\n clearTraceEvents()\n initializeTraceState({\n lastId: 0,\n shouldSaveTraceEvents: true,\n })\n const root = trace('next-build')\n root.traceChild('some-child-span').traceFn(() => null)\n recordTraceEvents(worker1Traces)\n expect(exportTraceState().lastId).toEqual(8)\n recordTraceEvents(worker2Traces)\n expect(exportTraceState().lastId).toEqual(13)\n root.traceChild('another-child-span').traceFn(() => null)\n root.stop()\n\n // Check that the final output looks correct.\n const allTraces = getTraceEvents()\n expect(allTraces.length).toEqual(7)\n const firstSpan = allTraces[0]\n expect(firstSpan.name).toEqual('some-child-span')\n expect(firstSpan.id).toEqual(2)\n expect(firstSpan.parentId).toEqual(1)\n\n const worker1Child = allTraces[1]\n expect(worker1Child.name).toEqual('webpack-compilation1')\n expect(worker1Child.id).toEqual(7)\n expect(worker1Child.parentId).toEqual(6)\n const worker1Root = allTraces[2]\n expect(worker1Root.name).toEqual('worker1')\n expect(worker1Root.id).toEqual(6)\n expect(worker1Root.parentId).toEqual(1)\n\n const worker2Child = allTraces[3]\n expect(worker2Child.name).toEqual('webpack-compilation2')\n expect(worker2Child.id).toEqual(12)\n expect(worker2Child.parentId).toEqual(11)\n const worker2Root = allTraces[4]\n expect(worker2Root.name).toEqual('worker2')\n expect(worker2Root.id).toEqual(11)\n expect(worker2Root.parentId).toEqual(1)\n\n const lastChildSpan = allTraces[5]\n expect(lastChildSpan.name).toEqual('another-child-span')\n expect(lastChildSpan.id).toEqual(14)\n expect(lastChildSpan.parentId).toEqual(1)\n\n const rootSpan = allTraces[6]\n expect(rootSpan.name).toEqual('next-build')\n expect(rootSpan.id).toEqual(1)\n expect(rootSpan.parentId).toBeUndefined()\n })\n })\n})\n"],"names":["traceEvent","name","duration","timestamp","id","startTime","tags","readSpans","file","readFileSync","split","filter","Boolean","flatMap","line","JSON","parse","readSpanNames","map","event","describe","tmpDirs","makeTmpDir","dir","mkdtemp","join","tmpdir","push","reporters","makeJsonReporter","args","reporter","createJsonReporter","beforeEach","initializeTraceState","lastId","shouldSaveTraceEvents","clearTraceEvents","setGlobal","undefined","afterAll","closeAllTraces","splice","close","Promise","all","rm","recursive","force","it","tmpDir","root","trace","traceChild","traceFn","traceAsyncFn","delayedPromise","resolve","setTimeout","stop","traceEvents","getTraceEvents","expect","length","toEqual","flushAllTraces","serializedTraces","toMatchObject","parentId","any","Number","startMs","Date","now","stopMs","msToNs","ms","BigInt","manualTraceChild","events","child","find","e","toBeDefined","PHASE_PRODUCTION_BUILD","filename","sizeLimit","Infinity","report","flushAll","distDir","PHASE_DEVELOPMENT_SERVER","fs","existsSync","toBe","i","toBeGreaterThan","build","rebuild","dev","first","repeat","second","limit","Buffer","byteLength","toBeLessThanOrEqual","names","written","endsWith","huge","writeSync","jest","spyOn","mockImplementation","Object","assign","Error","code","consoleLog","console","not","toThrow","toHaveBeenCalled","mockRestore","getId","traceState","exportTraceState","span","clone","stringify","defaultParentSpanId","worker1Span","worker1Traces","worker2Span","worker2Traces","recordTraceEvents","allTraces","firstSpan","worker1Child","worker1Root","worker2Child","worker2Root","lastChildSpan","rootSpan","toBeUndefined"],"mappings":";;;;0BAA4B;4DACK;sBACZ;oBACE;2BAIhB;wBAC4B;wBAGT;uBAUnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,SAASA,WAAWC,IAAY;IAC9B,OAAO;QACLA;QACAC,UAAU;QACVC,WAAW;QACXC,IAAI;QACJC,WAAW;QACXC,MAAM,CAAC;IACT;AACF;AAEA,qEAAqE;AACrE,0DAA0D;AAC1D,SAASC,UAAUC,IAAY;IAC7B,OAAOC,IAAAA,gBAAY,EAACD,MAAM,SACvBE,KAAK,CAAC,MACNC,MAAM,CAACC,SACPC,OAAO,CAAC,CAACC,OAASC,KAAKC,KAAK,CAACF;AAClC;AAEA,SAASG,cAAcT,IAAY;IACjC,OAAOD,UAAUC,MAAMU,GAAG,CAAC,CAACC,QAAUA,MAAMlB,IAAI;AAClD;AAEAmB,SAAS,SAAS;IAChB,MAAMC,UAAoB,EAAE;IAC5B,eAAeC;QACb,MAAMC,MAAM,MAAMC,IAAAA,iBAAO,EAACC,IAAAA,UAAI,EAACC,IAAAA,UAAM,KAAI;QACzCL,QAAQM,IAAI,CAACJ;QACb,OAAOA;IACT;IAEA,0EAA0E;IAC1E,2EAA2E;IAC3E,qEAAqE;IACrE,MAAMK,YAAwB,EAAE;IAChC,SAASC,iBACP,GAAGC,IAA2C;QAE9C,MAAMC,WAAWC,IAAAA,0BAAkB,KAAIF;QACvCF,UAAUD,IAAI,CAACI;QACf,OAAOA;IACT;IAEAE,WAAW;QACTC,IAAAA,2BAAoB,EAAC;YACnBC,QAAQ;YACRC,uBAAuB;QACzB;QACAC,IAAAA,uBAAgB;QAChB,oEAAoE;QACpEC,IAAAA,iBAAS,EAAC,WAAWC;QACrBD,IAAAA,iBAAS,EAAC,SAASC;IACrB;IAEAC,SAAS;QACP,0EAA0E;QAC1E,0EAA0E;QAC1E,gCAAgC;QAChCC,IAAAA,qBAAc;QACd,KAAK,MAAMV,YAAYH,UAAUc,MAAM,CAAC,GAAI;YAC1CX,SAASY,KAAK,oBAAdZ,SAASY,KAAK,MAAdZ;QACF;QACA,MAAMa,QAAQC,GAAG,CACfxB,QAAQqB,MAAM,CAAC,GAAGxB,GAAG,CAAC,CAACK,MAAQuB,IAAAA,YAAE,EAACvB,KAAK;gBAAEwB,WAAW;gBAAMC,OAAO;YAAK;IAE1E;IAEA5B,SAAS,UAAU;QACjB6B,GAAG,0BAA0B;YAC3B,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS;YAEnB,MAAMa,OAAOC,IAAAA,YAAK,EAAC,aAAab,WAAW;gBACzC,YAAY;YACd;YACAY,KAAKE,UAAU,CAAC,cAAcC,OAAO,CAAC,IAAM;YAC5C,MAAMH,KAAKE,UAAU,CAAC,oBAAoBE,YAAY,CAAC;gBACrD,MAAMC,iBAAiB,IAAIZ,QAAQ,CAACa;oBAClCC,WAAWD,SAAS;gBACtB;gBACA,MAAMD;YACR;YACAL,KAAKQ,IAAI;YACT,MAAMC,cAAcC,IAAAA,qBAAc;YAClCC,OAAOF,YAAYG,MAAM,EAAEC,OAAO,CAAC;YACnCF,OAAOF,WAAW,CAAC,EAAE,CAAC3D,IAAI,EAAE+D,OAAO,CAAC;YACpCF,OAAOF,WAAW,CAAC,EAAE,CAAC3D,IAAI,EAAE+D,OAAO,CAAC;YACpCF,OAAOF,WAAW,CAAC,EAAE,CAAC3D,IAAI,EAAE+D,OAAO,CAAC;YAEpC,4DAA4D;YAC5DC,IAAAA,qBAAc;YACd,MAAMC,mBAAmB3D,UAAUkB,IAAAA,UAAI,EAACyB,QAAQ;YAChDY,OAAOI,kBAAkBC,aAAa,CAAC;gBACrC;oBACE/D,IAAI;oBACJH,MAAM;oBACNmE,UAAU;oBACV/D,WAAWyD,OAAOO,GAAG,CAACC;oBACtBnE,WAAW2D,OAAOO,GAAG,CAACC;oBACtBpE,UAAU4D,OAAOO,GAAG,CAACC;oBACrBhE,MAAM,CAAC;gBACT;gBACA;oBACEF,IAAI;oBACJH,MAAM;oBACNmE,UAAU;oBACV/D,WAAWyD,OAAOO,GAAG,CAACC;oBACtBnE,WAAW2D,OAAOO,GAAG,CAACC;oBACtBpE,UAAU4D,OAAOO,GAAG,CAACC;oBACrBhE,MAAM,CAAC;gBACT;gBACA;oBACEF,IAAI;oBACJH,MAAM;oBACNI,WAAWyD,OAAOO,GAAG,CAACC;oBACtBnE,WAAW2D,OAAOO,GAAG,CAACC;oBACtBpE,UAAU4D,OAAOO,GAAG,CAACC;oBACrBhE,MAAM;wBACJ,YAAY;oBACd;gBACF;aACD;QACH;QAEA2C,GAAG,4DAA4D;YAC7D,MAAME,OAAOC,IAAAA,YAAK,EAAC;YACnB,uEAAuE;YACvE,sEAAsE;YACtE,2CAA2C;YAC3C,MAAMmB,UAAUC,KAAKC,GAAG,KAAK;YAC7B,MAAMC,SAASH,UAAU;YACzB,MAAMI,SAAS,CAACC,KAAeC,OAAOD,MAAMC,OAAO;YACnD1B,KAAK2B,gBAAgB,CAAC,gBAAgBH,OAAOJ,UAAUI,OAAOD;YAC9DvB,KAAKQ,IAAI;YAET,MAAMoB,SAASlB,IAAAA,qBAAc;YAC7B,MAAMmB,QAAQD,OAAOE,IAAI,CAAC,CAACC,IAAMA,EAAEjF,IAAI,KAAK;YAC5C6D,OAAOkB,OAAOG,WAAW;YACzB,wEAAwE;YACxE,uDAAuD;YACvDrB,OAAOkB,MAAO3E,SAAS,EAAE2D,OAAO,CAACO;YACjCT,OAAOkB,MAAO9E,QAAQ,EAAE8D,OAAO,CAAC;QAClC;QAEA,sEAAsE;QACtE,oDAAoD;QACpDf,GAAG,uCAAuC;YACxC,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YACzC,MAAMrD,WAAWF,iBAAiB;gBAChCwD,UAAU;gBACVC,WAAWC;YACb;YACA,MAAM/E,OAAOiB,IAAAA,UAAI,EAACyB,QAAQ;YAE1BnB,SAASyD,MAAM,CAACxF,WAAW;YAC3B+B,SAAS0D,QAAQ;YACjB3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAAC;aAAQ;YAE7C,6CAA6C;YAC7CjC,SAASyD,MAAM,CAACxF,WAAW;YAC3B+B,SAAS0D,QAAQ;YACjB1D,SAAS0D,QAAQ;YACjB3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAAC;gBAAS;aAAS;QACzD;QAEA,wEAAwE;QACxE,sEAAsE;QACtE,wEAAwE;QACxE,oEAAoE;QACpEf,GAAG,uDAAuD;YACxD,MAAMC,SAAS,MAAM5B;YACrB,MAAMoE,UAAUjE,IAAAA,UAAI,EAACyB,QAAQ;YAC7BZ,IAAAA,iBAAS,EAAC,WAAWoD;YACrBpD,IAAAA,iBAAS,EAAC,SAASqD,mCAAwB;YAC3C,MAAM5D,WAAWF,iBAAiB;gBAChCwD,UAAU;gBACVC,WAAWC;YACb;YAEAxD,SAASyD,MAAM,CAACxF,WAAW;YAC3B,oEAAoE;YACpE,6CAA6C;YAC7C8D,OAAO8B,WAAE,CAACC,UAAU,CAACH,UAAUI,IAAI,CAAC;YAEpC/D,SAAS0D,QAAQ;YACjB3B,OAAO7C,cAAcQ,IAAAA,UAAI,EAACiE,SAAS,WAAW1B,OAAO,CAAC;gBAAC;aAAW;QACpE;QAEAf,GAAG,4CAA4C;YAC7C,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YACzC,MAAMrD,WAAWF,iBAAiB;gBAChCwD,UAAU;gBACVC,WAAWC;YACb;YACA,MAAM/E,OAAOiB,IAAAA,UAAI,EAACyB,QAAQ;YAE1B,oEAAoE;YACpE,IAAK,IAAI6C,IAAI,GAAGA,IAAI,MAAMA,IAAK;gBAC7BhE,SAASyD,MAAM,CAACxF,WAAW,CAAC,KAAK,EAAE+F,GAAG;YACxC;YACAjC,OAAO7C,cAAcT,MAAMuD,MAAM,EAAEiC,eAAe,CAAC;YAEnDjE,SAAS0D,QAAQ;YACjB3B,OAAO7C,cAAcT,MAAMuD,MAAM,EAAE+B,IAAI,CAAC;QAC1C;QAEA7C,GAAG,sDAAsD;YACvD,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrB,MAAM1C,OAAOiB,IAAAA,UAAI,EAACyB,QAAQ;YAE1BZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YACzC,MAAMa,QAAQpE,iBAAiB;gBAC7BwD,UAAU;gBACVC,WAAWC;YACb;YACAU,MAAMT,MAAM,CAACxF,WAAW;YACxBiG,MAAMR,QAAQ;YACd3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAAC;aAAa;YAElD,qDAAqD;YACrD,MAAMkC,UAAUrE,iBAAiB;gBAC/BwD,UAAU;gBACVC,WAAWC;YACb;YACAW,QAAQV,MAAM,CAACxF,WAAW;YAC1BkG,QAAQT,QAAQ;YAChB3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAAC;aAAe;YAEpD,kDAAkD;YAClD1B,IAAAA,iBAAS,EAAC,SAASqD,mCAAwB;YAC3C,MAAMQ,MAAMtE,iBAAiB;gBAAEwD,UAAU;gBAASC,WAAWC;YAAS;YACtEY,IAAIX,MAAM,CAACxF,WAAW;YACtBmG,IAAIV,QAAQ;YACZ3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAAC;gBAAgB;aAAW;QAClE;QAEA,0EAA0E;QAC1E,uDAAuD;QACvDf,GAAG,uDAAuD;YACxD,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YACzC,MAAM5E,OAAOiB,IAAAA,UAAI,EAACyB,QAAQ;YAE1B,sEAAsE;YACtE,+CAA+C;YAC/C,MAAMkD,QAAQ,IAAIC,MAAM,CAAC;YACzB,MAAMC,SAAS,IAAID,MAAM,CAAC;YAC1B,MAAME,QAAQ;YACd,MAAMxE,WAAWF,iBAAiB;gBAChCwD,UAAU;gBACVC,WAAWiB;YACb;YAEAxE,SAASyD,MAAM,CAACxF,WAAWoG;YAC3BrE,SAAS0D,QAAQ;YACjB3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAACoC;aAAM;YAE3CrE,SAASyD,MAAM,CAACxF,WAAWsG;YAC3BvE,SAAS0D,QAAQ;YACjB3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAACsC;aAAO;YAC5CxC,OACE0C,OAAOC,UAAU,CAAChG,IAAAA,gBAAY,EAACD,MAAM,UAAU,SAC/CkG,mBAAmB,CAACH;QACxB;QAEA,oEAAoE;QACpE,iDAAiD;QACjDtD,GAAG,oDAAoD;YACrD,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YAEzC,kEAAkE;YAClE,mEAAmE;YACnE,qEAAqE;YACrE,uEAAuE;YACvE,IAAK,IAAIrB,SAAS,KAAKA,SAAS,KAAKA,SAAU;gBAC7C,MAAMhC,WAAWF,iBAAiB;oBAChCwD,UAAU,CAAC,MAAM,EAAEtB,QAAQ;oBAC3BuB,WAAWC;gBACb;gBACA,MAAMoB,QAAkB,EAAE;gBAC1B,IAAK,IAAIZ,IAAI,GAAGA,IAAI,KAAKA,IAAK;oBAC5B,MAAM9F,OAAO,IAAIoG,MAAM,CAACtC;oBACxB4C,MAAMhF,IAAI,CAAC1B;oBACX8B,SAASyD,MAAM,CAACxF,WAAWC;gBAC7B;gBACA8B,SAAS0D,QAAQ;gBAEjB,MAAMmB,UAAUnF,IAAAA,UAAI,EAACyB,QAAQ,CAAC,MAAM,EAAEa,QAAQ;gBAC9CD,OAAOrD,IAAAA,gBAAY,EAACmG,SAAS,SAASC,QAAQ,CAAC,QAAQf,IAAI,CAAC;gBAC5DhC,OAAO7C,cAAc2F,UAAU5C,OAAO,CAAC2C;YACzC;QACF;QAEA1D,GAAG,uCAAuC;YACxC,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YACzC,MAAMrD,WAAWF,iBAAiB;gBAChCwD,UAAU;gBACVC,WAAWC;YACb;YACA,MAAM/E,OAAOiB,IAAAA,UAAI,EAACyB,QAAQ;YAE1B,8BAA8B;YAC9B,MAAM4D,OAAO,IAAIT,MAAM,CAAC,MAAM;YAC9BtE,SAASyD,MAAM,CAACxF,WAAW;YAC3B+B,SAASyD,MAAM,CAACxF,WAAW8G;YAC3B/E,SAASyD,MAAM,CAACxF,WAAW;YAC3B+B,SAAS0D,QAAQ;YAEjB3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAAC;gBAAe8C;gBAAM;aAAa;QACzE;QAEA,qEAAqE;QACrE,sEAAsE;QACtE,qEAAqE;QACrE,yBAAyB;QACzB7D,GAAG,qDAAqD;YACtD,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YAEzC,oEAAoE;YACpE,wDAAwD;YACxD,IAAK,IAAIrB,SAAS,GAAGA,SAAS,KAAKA,SAAU;gBAC3C,MAAMhC,WAAWF,iBAAiB;oBAChCwD,UAAU,CAAC,MAAM,EAAEtB,QAAQ;oBAC3BuB,WAAWC;gBACb;gBACA,MAAMoB,QAAkB,EAAE;gBAC1B,IAAK,IAAIZ,IAAI,GAAGA,IAAI,KAAKA,IAAK;oBAC5B,MAAM9F,OAAO,GAAG,IAAIoG,MAAM,CAACtC,QAAQ,EAAE,EAAE,IAAIsC,MAAM,CAACN,IAAI,IAAI;oBAC1DY,MAAMhF,IAAI,CAAC1B;oBACX8B,SAASyD,MAAM,CAACxF,WAAWC;gBAC7B;gBACA8B,SAAS0D,QAAQ;gBAEjB3B,OAAO7C,cAAcQ,IAAAA,UAAI,EAACyB,QAAQ,CAAC,MAAM,EAAEa,QAAQ,IAAIC,OAAO,CAAC2C;YACjE;QACF;QAEA,uEAAuE;QACvE1D,GAAG,oCAAoC;YACrC,MAAMC,SAAS,MAAM5B;YACrBgB,IAAAA,iBAAS,EAAC,WAAWY;YACrBZ,IAAAA,iBAAS,EAAC,SAAS8C,iCAAsB;YACzC,MAAMrD,WAAWF,iBAAiB;gBAChCwD,UAAU;gBACVC,WAAWC;YACb;YACA,MAAM/E,OAAOiB,IAAAA,UAAI,EAACyB,QAAQ;YAE1BnB,SAASyD,MAAM,CAACxF,WAAW;YAC3B+B,SAAS0D,QAAQ;YAEjB,MAAMsB,YAAYC,KAAKC,KAAK,CAACrB,WAAE,EAAE,aAAasB,kBAAkB,CAAC;gBAC/D,MAAMC,OAAOC,MAAM,CAAC,IAAIC,MAAM,WAAW;oBAAEC,MAAM;gBAAS;YAC5D;YACA,MAAMC,aAAaP,KAAKC,KAAK,CAACO,SAAS,OAAON,kBAAkB,CAAC,KAAO;YACxE,IAAI;gBACFnF,SAASyD,MAAM,CAACxF,WAAW;gBAC3B8D,OAAO,IAAM/B,SAAS0D,QAAQ,IAAIgC,GAAG,CAACC,OAAO;gBAC7C5D,OAAOyD,YAAYI,gBAAgB;YACrC,SAAU;gBACRJ,WAAWK,WAAW;gBACtBb,UAAUa,WAAW;YACvB;YAEA7F,SAASyD,MAAM,CAACxF,WAAW;YAC3B+B,SAAS0D,QAAQ;YACjB3B,OAAO7C,cAAcT,OAAOwD,OAAO,CAAC;gBAAC;gBAAkB;aAAgB;QACzE;IACF;IAEA5C,SAAS,UAAU;QACjB6B,GAAG,uCAAuC;YACxC,MAAME,OAAOC,IAAAA,YAAK,EAAC;YACnBU,OAAOX,KAAK0E,KAAK,IAAI7D,OAAO,CAAC;YAC7B,MAAM8D,aAAaC,IAAAA,uBAAgB;YACnCjE,OAAOgE,WAAW3F,MAAM,EAAE6B,OAAO,CAAC;YAClC9B,IAAAA,2BAAoB,EAAC;gBACnBC,QAAQ;YACV;YACA,MAAM6F,OAAO5E,IAAAA,YAAK,EAAC;YACnBU,OAAOkE,KAAKH,KAAK,IAAI7D,OAAO,CAAC;QAC/B;QAEAf,GAAG,0CAA0C;YAC3C,MAAME,OAAOC,IAAAA,YAAK,EAAC;YACnBD,KAAKE,UAAU,CAAC,cAAcC,OAAO,CAAC,IAAM;YAC5CH,KAAKQ,IAAI;YACT,MAAMC,cAAcC,IAAAA,qBAAc;YAClCC,OAAOF,YAAYG,MAAM,EAAEC,OAAO,CAAC;YACnC,sEAAsE;YACtE,qEAAqE;YACrE,uBAAuB;YACvB,MAAMiE,QAAQlH,KAAKC,KAAK,CAACD,KAAKmH,SAAS,CAACtE;YACxCE,OAAOmE,OAAOjE,OAAO,CAACJ;QACxB;QAEAX,GAAG,sDAAsD;YACvD,mEAAmE;YACnE,yDAAyD;YACzD,mEAAmE;YACnEf,IAAAA,2BAAoB,EAAC;gBACnBC,QAAQ;gBACRgG,qBAAqB;gBACrB/F,uBAAuB;YACzB;YACA,MAAMgG,cAAchF,IAAAA,YAAK,EAAC;YAC1BgF,YAAY/E,UAAU,CAAC,wBAAwBC,OAAO,CAAC,IAAM;YAC7D8E,YAAYzE,IAAI;YAChB,MAAM0E,gBAAgBxE,IAAAA,qBAAc;YACpCC,OAAOuE,cAActE,MAAM,EAAEC,OAAO,CAAC;YAErC,8BAA8B;YAC9B3B,IAAAA,uBAAgB;YAChBH,IAAAA,2BAAoB,EAAC;gBACnBC,QAAQ;gBACRgG,qBAAqB;gBACrB/F,uBAAuB;YACzB;YACA,MAAMkG,cAAclF,IAAAA,YAAK,EAAC;YAC1BkF,YAAYjF,UAAU,CAAC,wBAAwBC,OAAO,CAAC,IAAM;YAC7DgF,YAAY3E,IAAI;YAChB,MAAM4E,gBAAgB1E,IAAAA,qBAAc;YACpCC,OAAOyE,cAAcxE,MAAM,EAAEC,OAAO,CAAC;YAErC,oEAAoE;YACpE,oBAAoB;YACpB3B,IAAAA,uBAAgB;YAChBH,IAAAA,2BAAoB,EAAC;gBACnBC,QAAQ;gBACRC,uBAAuB;YACzB;YACA,MAAMe,OAAOC,IAAAA,YAAK,EAAC;YACnBD,KAAKE,UAAU,CAAC,mBAAmBC,OAAO,CAAC,IAAM;YACjDkF,IAAAA,wBAAiB,EAACH;YAClBvE,OAAOiE,IAAAA,uBAAgB,IAAG5F,MAAM,EAAE6B,OAAO,CAAC;YAC1CwE,IAAAA,wBAAiB,EAACD;YAClBzE,OAAOiE,IAAAA,uBAAgB,IAAG5F,MAAM,EAAE6B,OAAO,CAAC;YAC1Cb,KAAKE,UAAU,CAAC,sBAAsBC,OAAO,CAAC,IAAM;YACpDH,KAAKQ,IAAI;YAET,6CAA6C;YAC7C,MAAM8E,YAAY5E,IAAAA,qBAAc;YAChCC,OAAO2E,UAAU1E,MAAM,EAAEC,OAAO,CAAC;YACjC,MAAM0E,YAAYD,SAAS,CAAC,EAAE;YAC9B3E,OAAO4E,UAAUzI,IAAI,EAAE+D,OAAO,CAAC;YAC/BF,OAAO4E,UAAUtI,EAAE,EAAE4D,OAAO,CAAC;YAC7BF,OAAO4E,UAAUtE,QAAQ,EAAEJ,OAAO,CAAC;YAEnC,MAAM2E,eAAeF,SAAS,CAAC,EAAE;YACjC3E,OAAO6E,aAAa1I,IAAI,EAAE+D,OAAO,CAAC;YAClCF,OAAO6E,aAAavI,EAAE,EAAE4D,OAAO,CAAC;YAChCF,OAAO6E,aAAavE,QAAQ,EAAEJ,OAAO,CAAC;YACtC,MAAM4E,cAAcH,SAAS,CAAC,EAAE;YAChC3E,OAAO8E,YAAY3I,IAAI,EAAE+D,OAAO,CAAC;YACjCF,OAAO8E,YAAYxI,EAAE,EAAE4D,OAAO,CAAC;YAC/BF,OAAO8E,YAAYxE,QAAQ,EAAEJ,OAAO,CAAC;YAErC,MAAM6E,eAAeJ,SAAS,CAAC,EAAE;YACjC3E,OAAO+E,aAAa5I,IAAI,EAAE+D,OAAO,CAAC;YAClCF,OAAO+E,aAAazI,EAAE,EAAE4D,OAAO,CAAC;YAChCF,OAAO+E,aAAazE,QAAQ,EAAEJ,OAAO,CAAC;YACtC,MAAM8E,cAAcL,SAAS,CAAC,EAAE;YAChC3E,OAAOgF,YAAY7I,IAAI,EAAE+D,OAAO,CAAC;YACjCF,OAAOgF,YAAY1I,EAAE,EAAE4D,OAAO,CAAC;YAC/BF,OAAOgF,YAAY1E,QAAQ,EAAEJ,OAAO,CAAC;YAErC,MAAM+E,gBAAgBN,SAAS,CAAC,EAAE;YAClC3E,OAAOiF,cAAc9I,IAAI,EAAE+D,OAAO,CAAC;YACnCF,OAAOiF,cAAc3I,EAAE,EAAE4D,OAAO,CAAC;YACjCF,OAAOiF,cAAc3E,QAAQ,EAAEJ,OAAO,CAAC;YAEvC,MAAMgF,WAAWP,SAAS,CAAC,EAAE;YAC7B3E,OAAOkF,SAAS/I,IAAI,EAAE+D,OAAO,CAAC;YAC9BF,OAAOkF,SAAS5I,EAAE,EAAE4D,OAAO,CAAC;YAC5BF,OAAOkF,SAAS5E,QAAQ,EAAE6E,aAAa;QACzC;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/types.d.ts b/e-commerce/node_modules/next/dist/trace/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c5c5b28bb321ce5d3d37b3c9d8bbfddeb8431e69 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/types.d.ts @@ -0,0 +1,16 @@ +export type SpanId = number; +export interface TraceState { + lastId: number; + defaultParentSpanId?: SpanId; + shouldSaveTraceEvents?: boolean; +} +export type TraceEvent = { + traceId?: string; + parentId?: SpanId; + name: string; + id: SpanId; + timestamp: number; + duration: number; + tags?: Record; + startTime?: number; +}; diff --git a/e-commerce/node_modules/next/dist/trace/types.js b/e-commerce/node_modules/next/dist/trace/types.js new file mode 100644 index 0000000000000000000000000000000000000000..f89b9ccce54e89b62b432c4802c4612600a703d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/types.js.map b/e-commerce/node_modules/next/dist/trace/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/upload-trace.d.ts b/e-commerce/node_modules/next/dist/trace/upload-trace.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f323cdb09e9c4532f7a28991fdfe2f500f42bddb --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/upload-trace.d.ts @@ -0,0 +1,8 @@ +export default function uploadTrace({ traceUploadUrl, mode, projectDir, distDir, isTurboSession, sync, }: { + traceUploadUrl: string; + mode: 'dev' | 'build'; + projectDir: string; + distDir: string; + isTurboSession: boolean; + sync?: boolean; +}): void; diff --git a/e-commerce/node_modules/next/dist/trace/upload-trace.js b/e-commerce/node_modules/next/dist/trace/upload-trace.js new file mode 100644 index 0000000000000000000000000000000000000000..08881ab2b29e98070b3ffb172a7a66797d5c6bb1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/upload-trace.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return uploadTrace; + } +}); +const _shared = require("./shared"); +const _storage = require("../telemetry/storage"); +function uploadTrace({ traceUploadUrl, mode, projectDir, distDir, isTurboSession, sync }) { + const { NEXT_TRACE_UPLOAD_DEBUG } = process.env; + const telemetry = new _storage.Telemetry({ + distDir + }); + // Note: cross-spawn is not used here as it causes + // a new command window to appear when we don't want it to + const child_process = require('child_process'); + // we use spawnSync when debugging to ensure logs are piped + // correctly to stdout/stderr + const spawn = NEXT_TRACE_UPLOAD_DEBUG || sync ? child_process.spawnSync : child_process.spawn; + spawn(process.execPath, [ + require.resolve('./trace-uploader'), + traceUploadUrl, + mode, + projectDir, + distDir, + String(isTurboSession), + _shared.traceId, + telemetry.anonymousId, + telemetry.sessionId + ], { + detached: !NEXT_TRACE_UPLOAD_DEBUG, + windowsHide: true, + shell: false, + ...NEXT_TRACE_UPLOAD_DEBUG ? { + stdio: 'inherit' + } : {} + }); +} + +//# sourceMappingURL=upload-trace.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/trace/upload-trace.js.map b/e-commerce/node_modules/next/dist/trace/upload-trace.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e2106052a8af017e2a56c2e1e2f51d208d2ce040 --- /dev/null +++ b/e-commerce/node_modules/next/dist/trace/upload-trace.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/trace/upload-trace.ts"],"sourcesContent":["import { traceId } from './shared'\nimport { Telemetry } from '../telemetry/storage'\n\nexport default function uploadTrace({\n traceUploadUrl,\n mode,\n projectDir,\n distDir,\n isTurboSession,\n sync,\n}: {\n traceUploadUrl: string\n mode: 'dev' | 'build'\n projectDir: string\n distDir: string\n isTurboSession: boolean\n sync?: boolean\n}) {\n const { NEXT_TRACE_UPLOAD_DEBUG } = process.env\n const telemetry = new Telemetry({ distDir })\n\n // Note: cross-spawn is not used here as it causes\n // a new command window to appear when we don't want it to\n const child_process =\n require('child_process') as typeof import('child_process')\n\n // we use spawnSync when debugging to ensure logs are piped\n // correctly to stdout/stderr\n const spawn =\n NEXT_TRACE_UPLOAD_DEBUG || sync\n ? child_process.spawnSync\n : child_process.spawn\n\n spawn(\n process.execPath,\n [\n require.resolve('./trace-uploader'),\n traceUploadUrl,\n mode,\n projectDir,\n distDir,\n String(isTurboSession),\n traceId,\n telemetry.anonymousId,\n telemetry.sessionId,\n ],\n {\n detached: !NEXT_TRACE_UPLOAD_DEBUG,\n windowsHide: true,\n shell: false,\n ...(NEXT_TRACE_UPLOAD_DEBUG\n ? {\n stdio: 'inherit',\n }\n : {}),\n }\n )\n}\n"],"names":["uploadTrace","traceUploadUrl","mode","projectDir","distDir","isTurboSession","sync","NEXT_TRACE_UPLOAD_DEBUG","process","env","telemetry","Telemetry","child_process","require","spawn","spawnSync","execPath","resolve","String","traceId","anonymousId","sessionId","detached","windowsHide","shell","stdio"],"mappings":";;;;+BAGA;;;eAAwBA;;;wBAHA;yBACE;AAEX,SAASA,YAAY,EAClCC,cAAc,EACdC,IAAI,EACJC,UAAU,EACVC,OAAO,EACPC,cAAc,EACdC,IAAI,EAQL;IACC,MAAM,EAAEC,uBAAuB,EAAE,GAAGC,QAAQC,GAAG;IAC/C,MAAMC,YAAY,IAAIC,kBAAS,CAAC;QAAEP;IAAQ;IAE1C,kDAAkD;IAClD,0DAA0D;IAC1D,MAAMQ,gBACJC,QAAQ;IAEV,2DAA2D;IAC3D,6BAA6B;IAC7B,MAAMC,QACJP,2BAA2BD,OACvBM,cAAcG,SAAS,GACvBH,cAAcE,KAAK;IAEzBA,MACEN,QAAQQ,QAAQ,EAChB;QACEH,QAAQI,OAAO,CAAC;QAChBhB;QACAC;QACAC;QACAC;QACAc,OAAOb;QACPc,eAAO;QACPT,UAAUU,WAAW;QACrBV,UAAUW,SAAS;KACpB,EACD;QACEC,UAAU,CAACf;QACXgB,aAAa;QACbC,OAAO;QACP,GAAIjB,0BACA;YACEkB,OAAO;QACT,IACA,CAAC,CAAC;IACR;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/types.d.ts b/e-commerce/node_modules/next/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a0c09bad0c3a158c82a3badb24d8dd2689484ef --- /dev/null +++ b/e-commerce/node_modules/next/dist/types.d.ts @@ -0,0 +1,232 @@ +/// +/// +/// +/// +/// +import type { Agent as HttpAgent } from 'http'; +import type { Agent as HttpsAgent } from 'https'; +import type { ParsedUrlQuery } from 'querystring'; +import type { IncomingMessage, ServerResponse } from 'http'; +import type { NextPageContext, NextComponentType, NextApiResponse, NextApiRequest, NextApiHandler } from './shared/lib/utils'; +import type { GetStaticPathsFallback } from './lib/fallback'; +import type { ParamMatchingMode } from './build/segment-config/app/app-segments'; +import type { NextApiRequestCookies } from './server/api-utils'; +import next from './server/next'; +export type ServerRuntime = 'nodejs' | 'experimental-edge' | 'edge' | undefined; +export { NextConfig } from './server/config'; +export type { NextAdapter, AdapterOutput } from './build/adapter/build-complete'; +export type { Metadata, MetadataRoute, ResolvedMetadata, ResolvingMetadata, Viewport, ResolvingViewport, ResolvedViewport, } from './lib/metadata/types/metadata-interface'; +export type { Instant } from './build/segment-config/app/app-segment-config'; +/** + * Optional contextual typing for parameter matching exports. Use + * `satisfies ParamMatching` to check modes without widening the object's keys, + * or provide parameter names for an explicit type annotation. + */ +export type ParamMatching = Partial>; +export type { Instrumentation } from './server/instrumentation/types'; +export type { RouterTransitionType, RouterTransitionPrefetchIntent, RouterTransitionEvent, RouterTransitionStartEvent, } from './client/router-transition-types'; +/** + * Stub route type for typedRoutes before `next dev` or `next build` is run + * @link https://nextjs.org/docs/app/api-reference/config/typescript#statically-typed-links + * @example + * ```ts + * import type { Route } from 'next' + * // ... + * router.push(returnToPath as Route) + * ``` + */ +export type Route = string & {}; +declare module 'react' { + interface ImgHTMLAttributes { + fetchPriority?: 'high' | 'low' | 'auto' | undefined; + } +} +export type Redirect = { + statusCode: 301 | 302 | 303 | 307 | 308; + destination: string; + basePath?: false; +} | { + permanent: boolean; + destination: string; + basePath?: false; +}; +/** + * `NextPage` type, use it as a guide to create `pages`. + */ +export type NextPage = NextComponentType; +export type FileSizeSuffix = `${'k' | 'K' | 'm' | 'M' | 'g' | 'G' | 't' | 'T' | 'p' | 'P'}${'b' | 'B'}`; +export type SizeLimit = number | `${number}${FileSizeSuffix}`; +export type ResponseLimit = SizeLimit | boolean; +/** + * `Config` type, use it for export const config + */ +export type PageConfig = { + api?: { + /** + * Configures or disables body size limit warning. Can take a number or + * any string format supported by `bytes`, for example `1000`, `'500kb'` or + * `'3mb'`. + */ + responseLimit?: ResponseLimit; + /** + * The byte limit of the body. This is the number of bytes or any string + * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + */ + bodyParser?: { + sizeLimit?: SizeLimit; + } | false; + /** + * Flag to disable warning "API page resolved + * without sending a response", due to explicitly + * using an external API resolver, like express + */ + externalResolver?: true; + }; + env?: Array; + /** + * Configures the longest time in seconds a serverless function can process an HTTP + * request before responding. + */ + maxDuration?: number; + runtime?: ServerRuntime; + unstable_runtimeJS?: false; + unstable_JsPreload?: false; +}; +export type { NextPageContext, NextComponentType, NextApiResponse, NextApiRequest, NextApiHandler, }; +export type PreviewData = string | false | object | undefined; +/** + * Context object passed into `getStaticProps`. + * @link https://nextjs.org/docs/api-reference/data-fetching/get-static-props#context-parameter + */ +export type GetStaticPropsContext = { + params?: Params; + preview?: boolean; + previewData?: Preview; + draftMode?: boolean; + locale?: string; + locales?: string[]; + defaultLocale?: string; + revalidateReason?: 'on-demand' | 'build' | 'stale'; +}; +/** + * The return type of `getStaticProps`. + * @link https://nextjs.org/docs/api-reference/data-fetching/get-static-props#getstaticprops-return-values + */ +export type GetStaticPropsResult = { + props: Props; + revalidate?: number | boolean; +} | { + redirect: Redirect; + revalidate?: number | boolean; +} | { + notFound: true; + revalidate?: number | boolean; +}; +/** + * Static Site Generation feature for Next.js. + * @link https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props + * @link https://nextjs.org/docs/pages/api-reference/config/typescript#static-generation-and-server-side-rendering + * @example + * ```ts + * export const getStaticProps: GetStaticProps = async (context) => { + * // ... + * } + * ``` + */ +export type GetStaticProps = (context: GetStaticPropsContext) => Promise> | GetStaticPropsResult; +export type InferGetStaticPropsType any> = Extract>, { + props: any; +}>['props']; +export type GetStaticPathsContext = { + locales?: string[]; + defaultLocale?: string; +}; +/** + * The return type of `getStaticPaths`. + * @link https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#getstaticpaths-return-values + */ +export type GetStaticPathsResult = { + paths: Array; + fallback: GetStaticPathsFallback; +}; +/** + * Define a list of paths to be statically generated if dynamic routes exist. + * @link https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-paths + * @link https://nextjs.org/docs/pages/api-reference/config/typescript#static-generation-and-server-side-rendering + * @example + * ```ts + * export const getStaticPaths: GetStaticPaths = async () => { + * // ... + * } + * ``` + */ +export type GetStaticPaths = (context: GetStaticPathsContext) => Promise> | GetStaticPathsResult; +/** + * Context object passed into `getServerSideProps`. + * @link https://nextjs.org/docs/pages/api-reference/functions/get-server-side-props#context-parameter + */ +export type GetServerSidePropsContext = { + req: IncomingMessage & { + cookies: NextApiRequestCookies; + }; + res: ServerResponse; + params?: Params; + query: ParsedUrlQuery; + preview?: boolean; + previewData?: Preview; + draftMode?: boolean; + resolvedUrl: string; + locale?: string; + locales?: string[]; + defaultLocale?: string; +}; +/** + * The return type of `getServerSideProps`. + * @link https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#getserversideprops-return-values + */ +export type GetServerSidePropsResult = { + props: Props | Promise; +} | { + redirect: Redirect; +} | { + notFound: true; +}; +/** + * Server-side Rendering feature for Next.js. + * @link https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props + * @link https://nextjs.org/docs/pages/api-reference/config/typescript#static-generation-and-server-side-rendering + * @example + * ```ts + * export const getServerSideProps: GetServerSideProps = async (context) => { + * // ... + * } + */ +export type GetServerSideProps = (context: GetServerSidePropsContext) => Promise>; +export type InferGetServerSidePropsType any> = Awaited>, { + props: any; +}>['props']>; +declare global { + interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: T): T; + randomUUID(): string; + } + var __NEXT_HTTP_AGENT_OPTIONS: { + keepAlive?: boolean; + } | undefined; + var __NEXT_UNDICI_AGENT_SET: boolean; + var __NEXT_HTTP_AGENT: HttpAgent; + var __NEXT_HTTPS_AGENT: HttpsAgent; +} +export default next; diff --git a/e-commerce/node_modules/next/document.d.ts b/e-commerce/node_modules/next/document.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..30a1ca701f3f1f00e7396feb45af7ae289aa36cc --- /dev/null +++ b/e-commerce/node_modules/next/document.d.ts @@ -0,0 +1,3 @@ +import Document from './dist/pages/_document' +export * from './dist/pages/_document' +export default Document diff --git a/e-commerce/node_modules/next/document.js b/e-commerce/node_modules/next/document.js new file mode 100644 index 0000000000000000000000000000000000000000..5741035f38add0041e07c106916735ee273fa429 --- /dev/null +++ b/e-commerce/node_modules/next/document.js @@ -0,0 +1 @@ +module.exports = require('./dist/pages/_document') diff --git a/e-commerce/node_modules/next/dynamic.d.ts b/e-commerce/node_modules/next/dynamic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0659b13ec241c0645df18600dccb3e5084f3599c --- /dev/null +++ b/e-commerce/node_modules/next/dynamic.d.ts @@ -0,0 +1,3 @@ +import dynamic from './dist/shared/lib/dynamic' +export * from './dist/shared/lib/dynamic' +export default dynamic diff --git a/e-commerce/node_modules/next/dynamic.js b/e-commerce/node_modules/next/dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..e2956e5f40337af0194d407d561a837a9a222627 --- /dev/null +++ b/e-commerce/node_modules/next/dynamic.js @@ -0,0 +1 @@ +module.exports = require('./dist/shared/lib/dynamic') diff --git a/e-commerce/node_modules/next/error.d.ts b/e-commerce/node_modules/next/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..528925335db15d4f1aea7f616f77efd269f0d0af --- /dev/null +++ b/e-commerce/node_modules/next/error.d.ts @@ -0,0 +1,7 @@ +// Default export is Pages Router only +import Error from './dist/api/error' +export * from './dist/api/error' +export default Error + +export { catchError } from './dist/api/error' +export type { ErrorInfo } from './dist/api/error' diff --git a/e-commerce/node_modules/next/error.js b/e-commerce/node_modules/next/error.js new file mode 100644 index 0000000000000000000000000000000000000000..ceafb96ea7fc2c9ed116ac099dee7c19c9840477 --- /dev/null +++ b/e-commerce/node_modules/next/error.js @@ -0,0 +1,9 @@ +module.exports = require('./dist/pages/_error') + +// Keep the catch-error graph lazy so default Error consumers do not load it. +Object.defineProperty(module.exports, 'catchError', { + enumerable: true, + get() { + return require('./dist/client/components/catch-error').catchError + }, +}) diff --git a/e-commerce/node_modules/next/experimental/testing/server.d.ts b/e-commerce/node_modules/next/experimental/testing/server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb4e9644177e6a48f73c64d96dedb94db2bcfabd --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testing/server.d.ts @@ -0,0 +1 @@ +export * from '../../dist/experimental/testing/server' diff --git a/e-commerce/node_modules/next/experimental/testing/server.js b/e-commerce/node_modules/next/experimental/testing/server.js new file mode 100644 index 0000000000000000000000000000000000000000..277b6541835fdf90ea33c95562fdf243371712c4 --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testing/server.js @@ -0,0 +1 @@ +module.exports = require('../../dist/experimental/testing/server') diff --git a/e-commerce/node_modules/next/experimental/testmode/playwright.d.ts b/e-commerce/node_modules/next/experimental/testmode/playwright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e87a445dddcf40f3e5467d94cd400c715f823e5 --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testmode/playwright.d.ts @@ -0,0 +1 @@ +export * from '../../dist/experimental/testmode/playwright' diff --git a/e-commerce/node_modules/next/experimental/testmode/playwright.js b/e-commerce/node_modules/next/experimental/testmode/playwright.js new file mode 100644 index 0000000000000000000000000000000000000000..b6ce1e2c343c983de77422c1e1a39da803face38 --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testmode/playwright.js @@ -0,0 +1 @@ +module.exports = require('../../dist/experimental/testmode/playwright') diff --git a/e-commerce/node_modules/next/experimental/testmode/playwright/msw.d.ts b/e-commerce/node_modules/next/experimental/testmode/playwright/msw.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e9e89b500c7cf5c8c4c1464a5b8750d266e2373 --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testmode/playwright/msw.d.ts @@ -0,0 +1 @@ +export * from '../../../dist/experimental/testmode/playwright/msw' diff --git a/e-commerce/node_modules/next/experimental/testmode/playwright/msw.js b/e-commerce/node_modules/next/experimental/testmode/playwright/msw.js new file mode 100644 index 0000000000000000000000000000000000000000..46c8b48f26247d5eb82c3369cae63d40f9d7aa9b --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testmode/playwright/msw.js @@ -0,0 +1 @@ +module.exports = require('../../../dist/experimental/testmode/playwright/msw') diff --git a/e-commerce/node_modules/next/experimental/testmode/proxy.d.ts b/e-commerce/node_modules/next/experimental/testmode/proxy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82ec16b54f5838d6c98fa748721765681f86f796 --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testmode/proxy.d.ts @@ -0,0 +1 @@ +export * from '../../dist/experimental/testmode/proxy' diff --git a/e-commerce/node_modules/next/experimental/testmode/proxy.js b/e-commerce/node_modules/next/experimental/testmode/proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..5abed8aa6f8bd87b8d96af753629f785e5841aa1 --- /dev/null +++ b/e-commerce/node_modules/next/experimental/testmode/proxy.js @@ -0,0 +1 @@ +module.exports = require('../../dist/experimental/testmode/proxy') diff --git a/e-commerce/node_modules/next/font/google/index.d.ts b/e-commerce/node_modules/next/font/google/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e651ded2329f93cc320408a5ac593b7c0467e7f5 --- /dev/null +++ b/e-commerce/node_modules/next/font/google/index.d.ts @@ -0,0 +1 @@ +export * from 'next/dist/compiled/@next/font/dist/google' diff --git a/e-commerce/node_modules/next/font/google/index.js b/e-commerce/node_modules/next/font/google/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/font/google/target.css b/e-commerce/node_modules/next/font/google/target.css new file mode 100644 index 0000000000000000000000000000000000000000..e3eb179b3405e8669b7d28ca63553624cdcdbb8c --- /dev/null +++ b/e-commerce/node_modules/next/font/google/target.css @@ -0,0 +1 @@ +/* target file for webpack loader */ diff --git a/e-commerce/node_modules/next/font/index.d.ts b/e-commerce/node_modules/next/font/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe10e31d59b927714096c2358fadc56cb62b2a62 --- /dev/null +++ b/e-commerce/node_modules/next/font/index.d.ts @@ -0,0 +1,30 @@ +export type AdjustFontFallback = { + fallbackFont: string + ascentOverride?: string + descentOverride?: string + lineGapOverride?: string + sizeAdjust?: string +} + +export type FontLoader = (options: { + functionName: string + variableName: string + data: any[] + emitFontFile: ( + content: Buffer, + ext: string, + preload: boolean, + isUsingSizeAdjust?: boolean + ) => string + resolve: (src: string) => string + isDev: boolean + isServer: boolean + loaderContext: any +}) => Promise<{ + css: string + fallbackFonts?: string[] + variable?: string + adjustFontFallback?: AdjustFontFallback + weight?: string + style?: string +}> diff --git a/e-commerce/node_modules/next/font/local/index.d.ts b/e-commerce/node_modules/next/font/local/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98d8cbb913c8d32fae1f7c64dc91d129fb5832d1 --- /dev/null +++ b/e-commerce/node_modules/next/font/local/index.d.ts @@ -0,0 +1 @@ +export { default } from 'next/dist/compiled/@next/font/dist/local' diff --git a/e-commerce/node_modules/next/font/local/index.js b/e-commerce/node_modules/next/font/local/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/font/local/target.css b/e-commerce/node_modules/next/font/local/target.css new file mode 100644 index 0000000000000000000000000000000000000000..e3eb179b3405e8669b7d28ca63553624cdcdbb8c --- /dev/null +++ b/e-commerce/node_modules/next/font/local/target.css @@ -0,0 +1 @@ +/* target file for webpack loader */ diff --git a/e-commerce/node_modules/next/form.d.ts b/e-commerce/node_modules/next/form.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e43c720f1bd2a9beeed978af772b9161facbad0 --- /dev/null +++ b/e-commerce/node_modules/next/form.d.ts @@ -0,0 +1,3 @@ +import Form from './dist/client/form' +export * from './dist/client/form' +export default Form diff --git a/e-commerce/node_modules/next/form.js b/e-commerce/node_modules/next/form.js new file mode 100644 index 0000000000000000000000000000000000000000..dfde00888f7010f2f5d25e885dff4cec56473ee1 --- /dev/null +++ b/e-commerce/node_modules/next/form.js @@ -0,0 +1 @@ +module.exports = require('./dist/client/form') diff --git a/e-commerce/node_modules/next/head.d.ts b/e-commerce/node_modules/next/head.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9cf09e9018339ae7e3ee7d3f543589e8b57891ae --- /dev/null +++ b/e-commerce/node_modules/next/head.d.ts @@ -0,0 +1,3 @@ +import Head from './dist/shared/lib/head' +export * from './dist/shared/lib/head' +export default Head diff --git a/e-commerce/node_modules/next/head.js b/e-commerce/node_modules/next/head.js new file mode 100644 index 0000000000000000000000000000000000000000..71758fdbeaa5cc3599559a3967623e3166223dba --- /dev/null +++ b/e-commerce/node_modules/next/head.js @@ -0,0 +1 @@ +module.exports = require('./dist/shared/lib/head') diff --git a/e-commerce/node_modules/next/headers.d.ts b/e-commerce/node_modules/next/headers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9317d037a84b35783345dc0abf94292ea5e2718 --- /dev/null +++ b/e-commerce/node_modules/next/headers.d.ts @@ -0,0 +1,3 @@ +export * from './dist/server/request/cookies' +export * from './dist/server/request/headers' +export * from './dist/server/request/draft-mode' diff --git a/e-commerce/node_modules/next/headers.js b/e-commerce/node_modules/next/headers.js new file mode 100644 index 0000000000000000000000000000000000000000..8e77c791748703e7863eefb46e67474800daf2cb --- /dev/null +++ b/e-commerce/node_modules/next/headers.js @@ -0,0 +1,3 @@ +module.exports.cookies = require('./dist/server/request/cookies').cookies +module.exports.headers = require('./dist/server/request/headers').headers +module.exports.draftMode = require('./dist/server/request/draft-mode').draftMode diff --git a/e-commerce/node_modules/next/image-types/global.d.ts b/e-commerce/node_modules/next/image-types/global.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..661c316e89b3c1aa5913b8afebdbf3e6299eccd7 --- /dev/null +++ b/e-commerce/node_modules/next/image-types/global.d.ts @@ -0,0 +1,61 @@ +// this file is conditionally added/removed to next-env.d.ts +// if the static image import handling is enabled + +declare module '*.png' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} + +declare module '*.svg' { + /** + * Use `any` to avoid conflicts with + * `@svgr/webpack` plugin or + * `babel-plugin-inline-react-svg` plugin. + */ + const content: any + + export default content +} + +declare module '*.jpg' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} + +declare module '*.jpeg' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} + +declare module '*.gif' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} + +declare module '*.webp' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} + +declare module '*.avif' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} + +declare module '*.ico' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} + +declare module '*.bmp' { + const content: import('../dist/shared/lib/image-external').StaticImageData + + export default content +} diff --git a/e-commerce/node_modules/next/image.d.ts b/e-commerce/node_modules/next/image.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6bb49fb54098791ad8f30c525b97b52398bf1f3 --- /dev/null +++ b/e-commerce/node_modules/next/image.d.ts @@ -0,0 +1,3 @@ +import Image from './dist/shared/lib/image-external' +export * from './dist/shared/lib/image-external' +export default Image diff --git a/e-commerce/node_modules/next/image.js b/e-commerce/node_modules/next/image.js new file mode 100644 index 0000000000000000000000000000000000000000..d344930f69e9dc3fa3e16549d24f69262a4641db --- /dev/null +++ b/e-commerce/node_modules/next/image.js @@ -0,0 +1 @@ +module.exports = require('./dist/shared/lib/image-external') diff --git a/e-commerce/node_modules/next/index.d.ts b/e-commerce/node_modules/next/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b0b7171b0f9772cd1e6ca3fc2f82d604431eae5 --- /dev/null +++ b/e-commerce/node_modules/next/index.d.ts @@ -0,0 +1,19 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +export { default } from './types' +export * from './types' diff --git a/e-commerce/node_modules/next/jest.d.ts b/e-commerce/node_modules/next/jest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0340983aa604d3f597748353334cfce852770bfa --- /dev/null +++ b/e-commerce/node_modules/next/jest.d.ts @@ -0,0 +1,3 @@ +import nextJest from './dist/build/jest/jest' +export * from './dist/build/jest/jest' +export default nextJest diff --git a/e-commerce/node_modules/next/jest.js b/e-commerce/node_modules/next/jest.js new file mode 100644 index 0000000000000000000000000000000000000000..adeca0379d6596a6f210a48a6ef87bf8de0b6de9 --- /dev/null +++ b/e-commerce/node_modules/next/jest.js @@ -0,0 +1 @@ +module.exports = require('./dist/build/jest/jest') diff --git a/e-commerce/node_modules/next/legacy/image.d.ts b/e-commerce/node_modules/next/legacy/image.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0007ba165a30b1a798b6688c1e863145e44c24d --- /dev/null +++ b/e-commerce/node_modules/next/legacy/image.d.ts @@ -0,0 +1,3 @@ +import Image from '../dist/client/legacy/image' +export * from '../dist/client/legacy/image' +export default Image diff --git a/e-commerce/node_modules/next/legacy/image.js b/e-commerce/node_modules/next/legacy/image.js new file mode 100644 index 0000000000000000000000000000000000000000..ca7e048c1d01b66853402af60402f5a0e1766acd --- /dev/null +++ b/e-commerce/node_modules/next/legacy/image.js @@ -0,0 +1 @@ +module.exports = require('../dist/client/legacy/image') diff --git a/e-commerce/node_modules/next/license.md b/e-commerce/node_modules/next/license.md new file mode 100644 index 0000000000000000000000000000000000000000..5948ee9bd0de5064423688a2967ab3111c2658ed --- /dev/null +++ b/e-commerce/node_modules/next/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2025 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/e-commerce/node_modules/next/link.d.ts b/e-commerce/node_modules/next/link.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb83179a5d2fde0606b9353b1d3b0ca77aa083f8 --- /dev/null +++ b/e-commerce/node_modules/next/link.d.ts @@ -0,0 +1,3 @@ +import Link from './dist/client/link' +export * from './dist/client/link' +export default Link diff --git a/e-commerce/node_modules/next/link.js b/e-commerce/node_modules/next/link.js new file mode 100644 index 0000000000000000000000000000000000000000..a37307be2e7385c730dce91dfbcf39d30c2173f5 --- /dev/null +++ b/e-commerce/node_modules/next/link.js @@ -0,0 +1 @@ +module.exports = require('./dist/client/link') diff --git a/e-commerce/node_modules/next/navigation-types/compat/navigation.d.ts b/e-commerce/node_modules/next/navigation-types/compat/navigation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..21192fdc0a1caf857647c7335133e04b6014930d --- /dev/null +++ b/e-commerce/node_modules/next/navigation-types/compat/navigation.d.ts @@ -0,0 +1,50 @@ +import type { ReadonlyURLSearchParams } from 'next/navigation' + +declare module 'next/navigation' { + /** + * Get a read-only URLSearchParams object. For example searchParams.get('foo') would return 'bar' when ?foo=bar + * Learn more about URLSearchParams here: https://developer.mozilla.org/docs/Web/API/URLSearchParams + * + * If used from `pages/`, the hook may return `null` when the router is not + * ready. + */ + export function useSearchParams(): ReadonlyURLSearchParams | null + + /** + * Get the current pathname. For example, if the URL is + * https://example.com/foo?bar=baz, the pathname would be /foo. + * + * If the hook is accessed from `pages/`, the pathname may be `null` when the + * router is not ready. + */ + export function usePathname(): string | null + + /** + * Get the current parameters. For example useParams() on /dashboard/[team] + * where pathname is /dashboard/nextjs would return { team: 'nextjs' } + * + * If used from `pages/`, the hook will return `null`. + */ + export function useParams< + T extends Record = Record< + string, + string | string[] + >, + >(): T | null + + /** + * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook + * that lets you read the active route segments **below** the Layout it is called from. + * + * If used from `pages/`, the hook will return `null`. + */ + export function useSelectedLayoutSegments(): string[] | null + + /** + * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook + * that lets you read the active route segment **one level below** the Layout it is called from. + * + * If used from `pages/`, the hook will return `null`. + */ + export function useSelectedLayoutSegment(): string | null +} diff --git a/e-commerce/node_modules/next/navigation.d.ts b/e-commerce/node_modules/next/navigation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..212649944829e677901532a3a63d58058ec29611 --- /dev/null +++ b/e-commerce/node_modules/next/navigation.d.ts @@ -0,0 +1 @@ +export * from './dist/client/components/navigation' diff --git a/e-commerce/node_modules/next/navigation.js b/e-commerce/node_modules/next/navigation.js new file mode 100644 index 0000000000000000000000000000000000000000..aa929f5938aae3beac8b36411058840290c6caae --- /dev/null +++ b/e-commerce/node_modules/next/navigation.js @@ -0,0 +1 @@ +module.exports = require('./dist/client/components/navigation') diff --git a/e-commerce/node_modules/next/node_modules/postcss/LICENSE b/e-commerce/node_modules/next/node_modules/postcss/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c2314d53d097cd36006110afd82fe3d09701a7c5 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2013 Andrey Sitnik + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/e-commerce/node_modules/next/node_modules/postcss/README.md b/e-commerce/node_modules/next/node_modules/postcss/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f9a20c442f912598bdfcfbe3de1cc0ffc050ac9c --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/README.md @@ -0,0 +1,24 @@ +# PostCSS + +Philosopher’s stone, logo of PostCSS + +PostCSS is a tool for transforming styles with JS plugins. +These plugins can lint your CSS, support variables and mixins, +transpile future CSS syntax, inline images, and more. + +PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba, +and JetBrains. The [Autoprefixer] and [Stylelint] PostCSS plugins are some of the most popular CSS tools. + +--- + +  PostCSS is built by 'atrule' + * charset.nodes //=> undefined + * + * const media = root.last + * media.nodes //=> [] + * ``` + */ +declare class AtRule_ extends Container { + /** + * An array containing the layer’s children. + * + * ```js + * const root = postcss.parse('@layer example { a { color: black } }') + * const layer = root.first + * layer.nodes.length //=> 1 + * layer.nodes[0].selector //=> 'a' + * ``` + * + * Can be `undefinded` if the at-rule has no body. + * + * ```js + * const root = postcss.parse('@layer a, b, c;') + * const layer = root.first + * layer.nodes //=> undefined + * ``` + */ + nodes: Container['nodes'] | undefined + parent: ContainerWithChildren | undefined + + raws: AtRule.AtRuleRaws + type: 'atrule' + /** + * The at-rule’s name immediately follows the `@`. + * + * ```js + * const root = postcss.parse('@media print {}') + * const media = root.first + * media.name //=> 'media' + * ``` + */ + get name(): string + set name(value: string) + + /** + * The at-rule’s parameters, the values that follow the at-rule’s name + * but precede any `{}` block. + * + * ```js + * const root = postcss.parse('@media print, screen {}') + * const media = root.first + * media.params //=> 'print, screen' + * ``` + */ + get params(): string + + set params(value: string) + + constructor(defaults?: AtRule.AtRuleProps) + assign(overrides: AtRule.AtRuleProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this +} + +declare class AtRule extends AtRule_ {} + +export = AtRule diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/at-rule.js b/e-commerce/node_modules/next/node_modules/postcss/lib/at-rule.js new file mode 100644 index 0000000000000000000000000000000000000000..9486447b029c6c9991ca1b62e5a5d57c611a7503 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/at-rule.js @@ -0,0 +1,25 @@ +'use strict' + +let Container = require('./container') + +class AtRule extends Container { + constructor(defaults) { + super(defaults) + this.type = 'atrule' + } + + append(...children) { + if (!this.proxyOf.nodes) this.nodes = [] + return super.append(...children) + } + + prepend(...children) { + if (!this.proxyOf.nodes) this.nodes = [] + return super.prepend(...children) + } +} + +module.exports = AtRule +AtRule.default = AtRule + +Container.registerAtRule(AtRule) diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/comment.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/comment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f764109b7a21c1527933d95bbfc2d5442834df40 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/comment.d.ts @@ -0,0 +1,67 @@ +import Container from './container.js' +import Node, { NodeProps } from './node.js' + +declare namespace Comment { + export interface CommentRaws extends Record { + /** + * The space symbols before the node. + */ + before?: string + + /** + * The space symbols between `/*` and the comment’s text. + */ + left?: string + + /** + * The space symbols between the comment’s text. + */ + right?: string + } + + export interface CommentProps extends NodeProps { + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: CommentRaws + /** Content of the comment. */ + text: string + } + + export { Comment_ as default } +} + +/** + * It represents a class that handles + * [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments) + * + * ```js + * Once (root, { Comment }) { + * const note = new Comment({ text: 'Note: …' }) + * root.append(note) + * } + * ``` + * + * Remember that CSS comments inside selectors, at-rule parameters, + * or declaration values will be stored in the `raws` properties + * explained above. + */ +declare class Comment_ extends Node { + parent: Container | undefined + raws: Comment.CommentRaws + type: 'comment' + /** + * The comment's text. + */ + get text(): string + + set text(value: string) + + constructor(defaults?: Comment.CommentProps) + assign(overrides: Comment.CommentProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this +} + +declare class Comment extends Comment_ {} + +export = Comment diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/comment.js b/e-commerce/node_modules/next/node_modules/postcss/lib/comment.js new file mode 100644 index 0000000000000000000000000000000000000000..c56650645caed3bb47cf7a39d18696ec47140ca3 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/comment.js @@ -0,0 +1,13 @@ +'use strict' + +let Node = require('./node') + +class Comment extends Node { + constructor(defaults) { + super(defaults) + this.type = 'comment' + } +} + +module.exports = Comment +Comment.default = Comment diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/container.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/container.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82b24d04c820194c888019fa449a1b15e8116aae --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/container.d.ts @@ -0,0 +1,478 @@ +import AtRule from './at-rule.js' +import Comment from './comment.js' +import Declaration from './declaration.js' +import Node, { ChildNode, ChildProps, NodeProps } from './node.js' +import { Root } from './postcss.js' +import Rule from './rule.js' + +declare namespace Container { + export type ContainerWithChildren = { + nodes: Child[] + } & (AtRule | Root | Rule) + + export interface ValueOptions { + /** + * String that’s used to narrow down values and speed up the regexp search. + */ + fast?: string + + /** + * An array of property names. + */ + props?: readonly string[] + } + + export interface ContainerProps extends NodeProps { + nodes?: readonly (ChildProps | Node)[] + } + + /** + * All types that can be passed into container methods to create or add a new + * child node. + */ + export type NewChild = + | ChildProps + | Node + | readonly ChildProps[] + | readonly Node[] + | readonly string[] + | string + | undefined + + export { Container_ as default } +} + +/** + * The `Root`, `AtRule`, and `Rule` container nodes + * inherit some common methods to help work with their children. + * + * Note that all containers can store any content. If you write a rule inside + * a rule, PostCSS will parse it. + */ +declare abstract class Container_ extends Node { + /** + * An array containing the container’s children. + * + * ```js + * const root = postcss.parse('a { color: black }') + * root.nodes.length //=> 1 + * root.nodes[0].selector //=> 'a' + * root.nodes[0].nodes[0].prop //=> 'color' + * ``` + */ + nodes: Child[] | undefined + + /** + * The container’s first child. + * + * ```js + * rule.first === rules.nodes[0] + * ``` + */ + get first(): Child | undefined + + /** + * The container’s last child. + * + * ```js + * rule.last === rule.nodes[rule.nodes.length - 1] + * ``` + */ + get last(): Child | undefined + /** + * Inserts new nodes to the end of the container. + * + * ```js + * const decl1 = new Declaration({ prop: 'color', value: 'black' }) + * const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) + * rule.append(decl1, decl2) + * + * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule + * root.append({ selector: 'a' }) // rule + * rule.append({ prop: 'color', value: 'black' }) // declaration + * rule.append({ text: 'Comment' }) // comment + * + * root.append('a {}') + * root.first.append('color: black; z-index: 1') + * ``` + * + * @param nodes New nodes. + * @return This node for methods chain. + */ + append(...nodes: Container.NewChild[]): this + assign(overrides: Container.ContainerProps | object): this + clone(overrides?: Partial): this + + cloneAfter(overrides?: Partial): this + + cloneBefore(overrides?: Partial): this + /** + * Iterates through the container’s immediate children, + * calling `callback` for each child. + * + * Returning `false` in the callback will break iteration. + * + * This method only iterates through the container’s immediate children. + * If you need to recursively iterate through all the container’s descendant + * nodes, use `Container#walk`. + * + * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe + * if you are mutating the array of child nodes during iteration. + * PostCSS will adjust the current index to match the mutations. + * + * ```js + * const root = postcss.parse('a { color: black; z-index: 1 }') + * const rule = root.first + * + * for (const decl of rule.nodes) { + * decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + * // Cycle will be infinite, because cloneBefore moves the current node + * // to the next index + * } + * + * rule.each(decl => { + * decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + * // Will be executed only for color and z-index + * }) + * ``` + * + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + each( + callback: (node: Child, index: number) => false | void + ): false | undefined + + /** + * Returns `true` if callback returns `true` + * for all of the container’s children. + * + * ```js + * const noPrefixes = rule.every(i => i.prop[0] !== '-') + * ``` + * + * @param condition Iterator returns true or false. + * @return Is every child pass condition. + */ + every( + condition: (node: Child, index: number, nodes: Child[]) => boolean + ): boolean + /** + * Returns a `child`’s index within the `Container#nodes` array. + * + * ```js + * rule.index( rule.nodes[2] ) //=> 2 + * ``` + * + * @param child Child of the current container. + * @return Child index. + */ + index(child: Child | number): number + + /** + * Insert new node after old node within the container. + * + * @param oldNode Child or child’s index. + * @param newNode New node. + * @return This node for methods chain. + */ + insertAfter(oldNode: Child | number, newNode: Container.NewChild): this + + /** + * Traverses the container’s descendant nodes, calling callback + * for each comment node. + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * ```js + * root.walkComments(comment => { + * comment.remove() + * }) + * ``` + * + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + + /** + * Insert new node before old node within the container. + * + * ```js + * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) + * ``` + * + * @param oldNode Child or child’s index. + * @param newNode New node. + * @return This node for methods chain. + */ + insertBefore(oldNode: Child | number, newNode: Container.NewChild): this + /** + * Inserts new nodes to the start of the container. + * + * ```js + * const decl1 = new Declaration({ prop: 'color', value: 'black' }) + * const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) + * rule.prepend(decl1, decl2) + * + * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule + * root.append({ selector: 'a' }) // rule + * rule.append({ prop: 'color', value: 'black' }) // declaration + * rule.append({ text: 'Comment' }) // comment + * + * root.append('a {}') + * root.first.append('color: black; z-index: 1') + * ``` + * + * @param nodes New nodes. + * @return This node for methods chain. + */ + prepend(...nodes: Container.NewChild[]): this + + /** + * Add child to the end of the node. + * + * ```js + * rule.push(new Declaration({ prop: 'color', value: 'black' })) + * ``` + * + * @param child New node. + * @return This node for methods chain. + */ + push(child: Child): this + + /** + * Removes all children from the container + * and cleans their parent properties. + * + * ```js + * rule.removeAll() + * rule.nodes.length //=> 0 + * ``` + * + * @return This node for methods chain. + */ + removeAll(): this + + /** + * Removes node from the container and cleans the parent properties + * from the node and its children. + * + * ```js + * rule.nodes.length //=> 5 + * rule.removeChild(decl) + * rule.nodes.length //=> 4 + * decl.parent //=> undefined + * ``` + * + * @param child Child or child’s index. + * @return This node for methods chain. + */ + removeChild(child: Child | number): this + + replaceValues( + pattern: RegExp | string, + replaced: { (substring: string, ...args: any[]): string } | string + ): this + /** + * Passes all declaration values within the container that match pattern + * through callback, replacing those values with the returned result + * of callback. + * + * This method is useful if you are using a custom unit or function + * and need to iterate through all values. + * + * ```js + * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { + * return 15 * parseInt(string) + 'px' + * }) + * ``` + * + * @param pattern Replace pattern. + * @param {object} options Options to speed up the search. + * @param replaced String to replace pattern or callback + * that returns a new value. The callback + * will receive the same arguments + * as those passed to a function parameter + * of `String#replace`. + * @return This node for methods chain. + */ + replaceValues( + pattern: RegExp | string, + options: Container.ValueOptions, + replaced: { (substring: string, ...args: any[]): string } | string + ): this + + /** + * Returns `true` if callback returns `true` for (at least) one + * of the container’s children. + * + * ```js + * const hasPrefix = rule.some(i => i.prop[0] === '-') + * ``` + * + * @param condition Iterator returns true or false. + * @return Is some child pass condition. + */ + some( + condition: (node: Child, index: number, nodes: Child[]) => boolean + ): boolean + + /** + * Traverses the container’s descendant nodes, calling callback + * for each node. + * + * Like container.each(), this method is safe to use + * if you are mutating arrays during iteration. + * + * If you only need to iterate through the container’s immediate children, + * use `Container#each`. + * + * ```js + * root.walk(node => { + * // Traverses all descendant nodes. + * }) + * ``` + * + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walk( + callback: (node: ChildNode, index: number) => false | void + ): false | undefined + + /** + * Traverses the container’s descendant nodes, calling callback + * for each at-rule node. + * + * If you pass a filter, iteration will only happen over at-rules + * that have matching names. + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * ```js + * root.walkAtRules(rule => { + * if (isOld(rule.name)) rule.remove() + * }) + * + * let first = false + * root.walkAtRules('charset', rule => { + * if (!first) { + * first = true + * } else { + * rule.remove() + * } + * }) + * ``` + * + * @param name String or regular expression to filter at-rules by name. + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walkAtRules( + nameFilter: RegExp | string, + callback: (atRule: AtRule, index: number) => false | void + ): false | undefined + walkAtRules( + callback: (atRule: AtRule, index: number) => false | void + ): false | undefined + + walkComments( + callback: (comment: Comment, indexed: number) => false | void + ): false | undefined + walkComments( + callback: (comment: Comment, indexed: number) => false | void + ): false | undefined + + /** + * Traverses the container’s descendant nodes, calling callback + * for each declaration node. + * + * If you pass a filter, iteration will only happen over declarations + * with matching properties. + * + * ```js + * root.walkDecls(decl => { + * checkPropertySupport(decl.prop) + * }) + * + * root.walkDecls('border-radius', decl => { + * decl.remove() + * }) + * + * root.walkDecls(/^background/, decl => { + * decl.value = takeFirstColorFromGradient(decl.value) + * }) + * ``` + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * @param prop String or regular expression to filter declarations + * by property name. + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walkDecls( + propFilter: RegExp | string, + callback: (decl: Declaration, index: number) => false | void + ): false | undefined + walkDecls( + callback: (decl: Declaration, index: number) => false | void + ): false | undefined + /** + * Traverses the container’s descendant nodes, calling callback + * for each rule node. + * + * If you pass a filter, iteration will only happen over rules + * with matching selectors. + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * ```js + * const selectors = [] + * root.walkRules(rule => { + * selectors.push(rule.selector) + * }) + * console.log(`Your CSS uses ${ selectors.length } selectors`) + * ``` + * + * @param selector String or regular expression to filter rules by selector. + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walkRules( + selectorFilter: RegExp | string, + callback: (rule: Rule, index: number) => false | void + ): false | undefined + walkRules( + callback: (rule: Rule, index: number) => false | void + ): false | undefined + /** + * An internal method that converts a {@link NewChild} into a list of actual + * child nodes that can then be added to this container. + * + * This ensures that the nodes' parent is set to this container, that they use + * the correct prototype chain, and that they're marked as dirty. + * + * @param mnodes The new node or nodes to add. + * @param sample A node from whose raws the new node's `before` raw should be + * taken. + * @param type This should be set to `'prepend'` if the new nodes will be + * inserted at the beginning of the container. + * @hidden + */ + protected normalize( + nodes: Container.NewChild, + sample: Node | undefined, + type?: 'prepend' | false + ): Child[] +} + +declare class Container< + Child extends Node = ChildNode +> extends Container_ {} + +export = Container diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/container.js b/e-commerce/node_modules/next/node_modules/postcss/lib/container.js new file mode 100644 index 0000000000000000000000000000000000000000..cd3b65b6f167e3da9f7294aa0bd824d072b1daa3 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/container.js @@ -0,0 +1,494 @@ +'use strict' + +let Comment = require('./comment') +let Declaration = require('./declaration') +let Node = require('./node') +let { isClean, my } = require('./symbols') + +let AtRule, parse, Root, Rule + +function cleanSource(nodes) { + let stack = nodes.slice() + while (stack.length > 0) { + let node = stack.pop() + delete node.source + if (node.nodes) { + node.nodes = node.nodes.slice() + for (let i of node.nodes) stack.push(i) + } + } + return nodes.slice() +} + +function markTreeDirty(node) { + let stack = [node] + while (stack.length > 0) { + let next = stack.pop() + next[isClean] = false + if (next.proxyOf.nodes) { + for (let i of next.proxyOf.nodes) stack.push(i) + } + } +} + +class Container extends Node { + get first() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[0] + } + + get last() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[this.proxyOf.nodes.length - 1] + } + + append(...children) { + for (let child of children) { + let nodes = this.normalize(child, this.last) + for (let node of nodes) this.proxyOf.nodes.push(node) + } + + this.markDirty() + + return this + } + + cleanRaws(keepBetween) { + let stack = [this] + while (stack.length > 0) { + let node = stack.pop() + if (node !== this && node.cleanRaws !== Container.prototype.cleanRaws) { + // Subclass with own logic; let it handle its subtree + node.cleanRaws(keepBetween) + continue + } + Node.prototype.cleanRaws.call(node, keepBetween) + if (node.nodes) { + for (let child of node.nodes) stack.push(child) + } + } + } + + each(callback) { + if (!this.proxyOf.nodes) return undefined + let iterator = this.getIterator() + + let index, result + while (this.indexes[iterator] < this.proxyOf.nodes.length) { + index = this.indexes[iterator] + result = callback(this.proxyOf.nodes[index], index) + if (result === false) break + + this.indexes[iterator] += 1 + } + + delete this.indexes[iterator] + return result + } + + every(condition) { + return this.nodes.every(condition) + } + + getIterator() { + if (!this.lastEach) this.lastEach = 0 + if (!this.indexes) this.indexes = {} + + this.lastEach += 1 + let iterator = this.lastEach + this.indexes[iterator] = 0 + + return iterator + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (!node[prop]) { + return node[prop] + } else if ( + prop === 'each' || + (typeof prop === 'string' && prop.startsWith('walk')) + ) { + return (...args) => { + return node[prop]( + ...args.map(i => { + if (typeof i === 'function') { + return (child, index) => i(child.toProxy(), index) + } else { + return i + } + }) + ) + } + } else if (prop === 'every' || prop === 'some') { + return cb => { + return node[prop]((child, ...other) => + cb(child.toProxy(), ...other) + ) + } + } else if (prop === 'root') { + return () => node.root().toProxy() + } else if (prop === 'nodes') { + return node.nodes.map(i => i.toProxy()) + } else if (prop === 'first' || prop === 'last') { + return node[prop].toProxy() + } else { + return node[prop] + } + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if (prop === 'name' || prop === 'params' || prop === 'selector') { + node.markDirty() + } + return true + } + } + } + + index(child) { + if (typeof child === 'number') return child + if (child.proxyOf) child = child.proxyOf + return this.proxyOf.nodes.indexOf(child) + } + + insertAfter(exist, add) { + let existIndex = this.index(exist) + let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse() + existIndex = this.index(exist) + for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (existIndex < index) { + this.indexes[id] = index + nodes.length + } + } + + this.markDirty() + + return this + } + + insertBefore(exist, add) { + let existIndex = this.index(exist) + let type = existIndex === 0 ? 'prepend' : false + let nodes = this.normalize( + add, + this.proxyOf.nodes[existIndex], + type + ).reverse() + existIndex = this.index(exist) + for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (existIndex <= index) { + this.indexes[id] = index + nodes.length + } + } + + this.markDirty() + + return this + } + + normalize(nodes, sample) { + if (typeof nodes === 'string') { + nodes = cleanSource(parse(nodes).nodes) + } else if (typeof nodes === 'undefined') { + nodes = [] + } else if (Array.isArray(nodes)) { + nodes = nodes.slice(0) + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore') + } + } else if (nodes.type === 'root' && this.type !== 'document') { + nodes = nodes.nodes.slice(0) + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore') + } + } else if (nodes.type) { + nodes = [nodes] + } else if (nodes.prop) { + if (typeof nodes.value === 'undefined') { + throw new Error('Value field is missed in node creation') + } else if (typeof nodes.value !== 'string') { + nodes.value = String(nodes.value) + } + nodes = [new Declaration(nodes)] + } else if (nodes.selector || nodes.selectors) { + nodes = [new Rule(nodes)] + } else if (nodes.name) { + nodes = [new AtRule(nodes)] + } else if (nodes.text) { + nodes = [new Comment(nodes)] + } else { + throw new Error('Unknown node type in node creation') + } + + let processed = nodes.map(i => { + /* c8 ignore next */ + if (!i[my]) Container.rebuild(i) + i = i.proxyOf + if (i.parent) i.parent.removeChild(i) + if (i[isClean]) markTreeDirty(i) + + if (!i.raws) i.raws = {} + if (typeof i.raws.before === 'undefined') { + if (sample && typeof sample.raws.before !== 'undefined') { + i.raws.before = sample.raws.before.replace(/\S/g, '') + } + } + i.parent = this.proxyOf + return i + }) + + return processed + } + + prepend(...children) { + children = children.reverse() + for (let child of children) { + let nodes = this.normalize(child, this.first, 'prepend').reverse() + for (let node of nodes) this.proxyOf.nodes.unshift(node) + for (let id in this.indexes) { + this.indexes[id] = this.indexes[id] + nodes.length + } + } + + this.markDirty() + + return this + } + + push(child) { + child.parent = this + this.proxyOf.nodes.push(child) + return this + } + + removeAll() { + for (let node of this.proxyOf.nodes) node.parent = undefined + this.proxyOf.nodes = [] + + this.markDirty() + + return this + } + + removeChild(child) { + child = this.index(child) + this.proxyOf.nodes[child].parent = undefined + this.proxyOf.nodes.splice(child, 1) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (index >= child) { + this.indexes[id] = index - 1 + } + } + + this.markDirty() + + return this + } + + replaceValues(pattern, opts, callback) { + if (!callback) { + callback = opts + opts = {} + } + + this.walkDecls(decl => { + if (opts.props && !opts.props.includes(decl.prop)) return + if (opts.fast && !decl.value.includes(opts.fast)) return + + decl.value = decl.value.replace(pattern, callback) + }) + + this.markDirty() + + return this + } + + some(condition) { + return this.nodes.some(condition) + } + + walk(callback) { + if (!this.proxyOf.nodes) return undefined + + // An explicit stack instead of recursive `each()` calls to survive + // deeply nested trees. Each frame keeps a live `indexes` slot, so + // insertion and removal during the walk behave like `each()`: the + // slot stays at the current child until its subtree is finished. + let stack = [{ iterator: this.getIterator(), node: this.proxyOf }] + + while (stack.length > 0) { + let { iterator, node } = stack[stack.length - 1] + let index = node.indexes[iterator] + + if (index >= node.proxyOf.nodes.length) { + delete node.indexes[iterator] + stack.pop() + let parent = stack[stack.length - 1] + // Finish the parent’s step for the child subtree we just left + if (parent) parent.node.indexes[parent.iterator] += 1 + continue + } + + let child = node.proxyOf.nodes[index] + let result + try { + result = callback(child, index) + } catch (e) { + throw child.addToError(e) + } + if (result === false) { + for (let opened of stack) { + delete opened.node.indexes[opened.iterator] + } + return false + } + if (child.walk && child.proxyOf.nodes) { + stack.push({ iterator: child.getIterator(), node: child }) + } else { + node.indexes[iterator] += 1 + } + } + + return undefined + } + + walkAtRules(name, callback) { + if (!callback) { + callback = name + return this.walk((child, i) => { + if (child.type === 'atrule') { + return callback(child, i) + } + }) + } + if (name instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'atrule' && name.test(child.name)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'atrule' && child.name === name) { + return callback(child, i) + } + }) + } + + walkComments(callback) { + return this.walk((child, i) => { + if (child.type === 'comment') { + return callback(child, i) + } + }) + } + + walkDecls(prop, callback) { + if (!callback) { + callback = prop + return this.walk((child, i) => { + if (child.type === 'decl') { + return callback(child, i) + } + }) + } + if (prop instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'decl' && prop.test(child.prop)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'decl' && child.prop === prop) { + return callback(child, i) + } + }) + } + + walkRules(selector, callback) { + if (!callback) { + callback = selector + + return this.walk((child, i) => { + if (child.type === 'rule') { + return callback(child, i) + } + }) + } + if (selector instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'rule' && selector.test(child.selector)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'rule' && child.selector === selector) { + return callback(child, i) + } + }) + } +} + +Container.registerParse = dependant => { + parse = dependant +} + +Container.registerRule = dependant => { + Rule = dependant +} + +Container.registerAtRule = dependant => { + AtRule = dependant +} + +Container.registerRoot = dependant => { + Root = dependant +} + +module.exports = Container +Container.default = Container + +/* c8 ignore start */ +Container.rebuild = node => { + let stack = [node] + while (stack.length > 0) { + let next = stack.pop() + if (next.type === 'atrule') { + Object.setPrototypeOf(next, AtRule.prototype) + } else if (next.type === 'rule') { + Object.setPrototypeOf(next, Rule.prototype) + } else if (next.type === 'decl') { + Object.setPrototypeOf(next, Declaration.prototype) + } else if (next.type === 'comment') { + Object.setPrototypeOf(next, Comment.prototype) + } else if (next.type === 'root') { + Object.setPrototypeOf(next, Root.prototype) + } + + next[my] = true + + if (next.nodes) { + for (let child of next.nodes) stack.push(child) + } + } +} +/* c8 ignore stop */ diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/css-syntax-error.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/css-syntax-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..03d9ed1766f78a8472f7b2485a7cf0f40cb89525 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/css-syntax-error.d.ts @@ -0,0 +1,247 @@ +import { FilePosition } from './input.js' + +declare namespace CssSyntaxError { + /** + * A position that is part of a range. + */ + export interface RangePosition { + /** + * The column number in the input. + */ + column: number + + /** + * The line number in the input. + */ + line: number + } + + export { CssSyntaxError_ as default } +} + +/** + * The CSS parser throws this error for broken CSS. + * + * Custom parsers can throw this error for broken custom syntax using + * the `Node#error` method. + * + * PostCSS will use the input source map to detect the original error location. + * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, + * PostCSS will show the original position in the Sass file. + * + * If you need the position in the PostCSS input + * (e.g., to debug the previous compiler), use `error.input.file`. + * + * ```js + * // Raising error from plugin + * throw node.error('Unknown variable', { plugin: 'postcss-vars' }) + * ``` + * + * ```js + * // Catching and checking syntax error + * try { + * postcss.parse('a{') + * } catch (error) { + * if (error.name === 'CssSyntaxError') { + * error //=> CssSyntaxError + * } + * } + * ``` + */ +declare class CssSyntaxError_ extends Error { + /** + * Source column of the error. + * + * ```js + * error.column //=> 1 + * error.input.column //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.column`. + */ + column?: number + + /** + * Source column of the error's end, exclusive. Provided if the error pertains + * to a range. + * + * ```js + * error.endColumn //=> 1 + * error.input.endColumn //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.endColumn`. + */ + endColumn?: number + + /** + * Source line of the error's end, exclusive. Provided if the error pertains + * to a range. + * + * ```js + * error.endLine //=> 3 + * error.input.endLine //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.endLine`. + */ + endLine?: number + + /** + * Absolute path to the broken file. + * + * ```js + * error.file //=> 'a.sass' + * error.input.file //=> 'a.css' + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.file`. + */ + file?: string + + /** + * Input object with PostCSS internal information + * about input file. If input has source map + * from previous tool, PostCSS will use origin + * (for example, Sass) source. You can use this + * object to get PostCSS input source. + * + * ```js + * error.input.file //=> 'a.css' + * error.file //=> 'a.sass' + * ``` + */ + input?: FilePosition + + /** + * Source line of the error. + * + * ```js + * error.line //=> 2 + * error.input.line //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.line`. + */ + line?: number + + /** + * Full error text in the GNU error format + * with plugin, file, line and column. + * + * ```js + * error.message //=> 'a.css:1:1: Unclosed block' + * ``` + */ + message: string + + /** + * Always equal to `'CssSyntaxError'`. You should always check error type + * by `error.name === 'CssSyntaxError'` + * instead of `error instanceof CssSyntaxError`, + * because npm could have several PostCSS versions. + * + * ```js + * if (error.name === 'CssSyntaxError') { + * error //=> CssSyntaxError + * } + * ``` + */ + name: 'CssSyntaxError' + + /** + * Plugin name, if error came from plugin. + * + * ```js + * error.plugin //=> 'postcss-vars' + * ``` + */ + plugin?: string + + /** + * Error message. + * + * ```js + * error.message //=> 'Unclosed block' + * ``` + */ + reason: string + + /** + * Source code of the broken file. + * + * ```js + * error.source //=> 'a { b {} }' + * error.input.source //=> 'a b { }' + * ``` + */ + source?: string + + stack: string + + /** + * Instantiates a CSS syntax error. Can be instantiated for a single position + * or for a range. + * @param message Error message. + * @param lineOrStartPos If for a single position, the line number, or if for + * a range, the inclusive start position of the error. + * @param columnOrEndPos If for a single position, the column number, or if for + * a range, the exclusive end position of the error. + * @param source Source code of the broken file. + * @param file Absolute path to the broken file. + * @param plugin PostCSS plugin name, if error came from plugin. + */ + constructor( + message: string, + lineOrStartPos?: CssSyntaxError.RangePosition | number, + columnOrEndPos?: CssSyntaxError.RangePosition | number, + source?: string, + file?: string, + plugin?: string + ) + + /** + * Returns a few lines of CSS source that caused the error. + * + * If the CSS has an input source map without `sourceContent`, + * this method will return an empty string. + * + * ```js + * error.showSourceCode() //=> " 4 | } + * // 5 | a { + * // > 6 | bad + * // | ^ + * // 7 | } + * // 8 | b {" + * ``` + * + * @param color Whether arrow will be colored red by terminal + * color codes. By default, PostCSS will detect + * color support by `process.stdout.isTTY` + * and `process.env.NODE_DISABLE_COLORS`. + * @return Few lines of CSS source that caused the error. + */ + showSourceCode(color?: boolean): string + + /** + * Returns error position, message and source code of the broken part. + * + * ```js + * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block + * // > 1 | a { + * // | ^" + * ``` + * + * @return Error position, message and source code. + */ + toString(): string +} + +declare class CssSyntaxError extends CssSyntaxError_ {} + +export = CssSyntaxError diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/css-syntax-error.js b/e-commerce/node_modules/next/node_modules/postcss/lib/css-syntax-error.js new file mode 100644 index 0000000000000000000000000000000000000000..275a4f64c2f8df215341a74d61e2aa2d05d61f78 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/css-syntax-error.js @@ -0,0 +1,133 @@ +'use strict' + +let pico = require('picocolors') + +let terminalHighlight = require('./terminal-highlight') + +class CssSyntaxError extends Error { + constructor(message, line, column, source, file, plugin) { + super(message) + this.name = 'CssSyntaxError' + this.reason = message + + if (file) { + this.file = file + } + if (source) { + this.source = source + } + if (plugin) { + this.plugin = plugin + } + if (typeof line !== 'undefined' && typeof column !== 'undefined') { + if (typeof line === 'number') { + this.line = line + this.column = column + } else { + this.line = line.line + this.column = line.column + this.endLine = column.line + this.endColumn = column.column + } + } + + this.setMessage() + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, CssSyntaxError) + } + } + + setMessage() { + this.message = this.plugin ? this.plugin + ': ' : '' + this.message += this.file ? this.file : '' + if (typeof this.line !== 'undefined') { + this.message += ':' + this.line + ':' + this.column + } + this.message += ': ' + this.reason + } + + showSourceCode(color) { + if (!this.source) return '' + + let css = this.source + if (color == null) color = pico.isColorSupported + + let aside = text => text + let mark = text => text + let highlight = text => text + if (color) { + let { bold, gray, red } = pico.createColors(true) + mark = text => bold(red(text)) + aside = text => gray(text) + if (terminalHighlight) { + highlight = text => terminalHighlight(text) + } + } + + let lines = css.split(/\r?\n/) + let start = Math.max(this.line - 3, 0) + let end = Math.min(this.line + 2, lines.length) + let maxWidth = String(end).length + + return lines + .slice(start, end) + .map((line, index) => { + let number = start + 1 + index + let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ' + if (number === this.line) { + if (line.length > 160) { + let padding = 20 + let subLineStart = Math.max(0, this.column - padding) + let subLineEnd = Math.max( + this.column + padding, + this.endColumn + padding + ) + let subLine = line.slice(subLineStart, subLineEnd) + + let spacing = + aside(gutter.replace(/\d/g, ' ')) + + line + .slice(0, Math.min(this.column - 1, padding - 1)) + .replace(/[^\t]/g, ' ') + + return ( + mark('>') + + aside(gutter) + + highlight(subLine) + + '\n ' + + spacing + + mark('^') + ) + } + + let spacing = + aside(gutter.replace(/\d/g, ' ')) + + line.slice(0, this.column - 1).replace(/[^\t]/g, ' ') + + return ( + mark('>') + + aside(gutter) + + highlight(line) + + '\n ' + + spacing + + mark('^') + ) + } + + return ' ' + aside(gutter) + highlight(line) + }) + .join('\n') + } + + toString() { + let code = this.showSourceCode() + if (code) { + code = '\n\n' + code + '\n' + } + return this.name + ': ' + this.message + code + } +} + +module.exports = CssSyntaxError +CssSyntaxError.default = CssSyntaxError diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/declaration.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/declaration.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..55dec7f8b4369a82301a9f2456f4c55860bcccb5 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/declaration.d.ts @@ -0,0 +1,150 @@ +import { ContainerWithChildren } from './container.js' +import Node from './node.js' + +declare namespace Declaration { + export interface DeclarationRaws extends Record { + /** + * The space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + */ + before?: string + + /** + * The symbols between the property and value for declarations. + */ + between?: string + + /** + * The content of the important statement, if it is not just `!important`. + */ + important?: string + + /** + * Declaration value with comments. + */ + value?: { + raw: string + value: string + } + } + + export interface DeclarationProps { + /** Whether the declaration has an `!important` annotation. */ + important?: boolean + /** Name of the declaration. */ + prop: string + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: DeclarationRaws + /** Value of the declaration. */ + value: string + } + + export { Declaration_ as default } +} + +/** + * It represents a class that handles + * [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations) + * + * ```js + * Once (root, { Declaration }) { + * const color = new Declaration({ prop: 'color', value: 'black' }) + * root.append(color) + * } + * ``` + * + * ```js + * const root = postcss.parse('a { color: black }') + * const decl = root.first?.first + * + * decl.type //=> 'decl' + * decl.toString() //=> ' color: black' + * ``` + */ +declare class Declaration_ extends Node { + parent: ContainerWithChildren | undefined + raws: Declaration.DeclarationRaws + + type: 'decl' + + /** + * It represents a specificity of the declaration. + * + * If true, the CSS declaration will have an + * [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) + * specifier. + * + * ```js + * const root = postcss.parse('a { color: black !important; color: red }') + * + * root.first.first.important //=> true + * root.first.last.important //=> undefined + * ``` + */ + get important(): boolean + set important(value: boolean) + + /** + * The property name for a CSS declaration. + * + * ```js + * const root = postcss.parse('a { color: black }') + * const decl = root.first.first + * + * decl.prop //=> 'color' + * ``` + */ + get prop(): string + + set prop(value: string) + + /** + * The property value for a CSS declaration. + * + * Any CSS comments inside the value string will be filtered out. + * CSS comments present in the source value will be available in + * the `raws` property. + * + * Assigning new `value` would ignore the comments in `raws` + * property while compiling node to string. + * + * ```js + * const root = postcss.parse('a { color: black }') + * const decl = root.first.first + * + * decl.value //=> 'black' + * ``` + */ + get value(): string + set value(value: string) + + /** + * It represents a getter that returns `true` if a declaration starts with + * `--` or `$`, which are used to declare variables in CSS and SASS/SCSS. + * + * ```js + * const root = postcss.parse(':root { --one: 1 }') + * const one = root.first.first + * + * one.variable //=> true + * ``` + * + * ```js + * const root = postcss.parse('$one: 1') + * const one = root.first + * + * one.variable //=> true + * ``` + */ + get variable(): boolean + constructor(defaults?: Declaration.DeclarationProps) + + assign(overrides: Declaration.DeclarationProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this +} + +declare class Declaration extends Declaration_ {} + +export = Declaration diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/declaration.js b/e-commerce/node_modules/next/node_modules/postcss/lib/declaration.js new file mode 100644 index 0000000000000000000000000000000000000000..65a03aa961edbdb25aecc840bab6843f1e7ea6c0 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/declaration.js @@ -0,0 +1,24 @@ +'use strict' + +let Node = require('./node') + +class Declaration extends Node { + get variable() { + return this.prop.startsWith('--') || this.prop[0] === '$' + } + + constructor(defaults) { + if ( + defaults && + typeof defaults.value !== 'undefined' && + typeof defaults.value !== 'string' + ) { + defaults = { ...defaults, value: String(defaults.value) } + } + super(defaults) + this.type = 'decl' + } +} + +module.exports = Declaration +Declaration.default = Declaration diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/document.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/document.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67194dd9ca31ddd2015121d9cd797deb8e7101a7 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/document.d.ts @@ -0,0 +1,68 @@ +import Container, { ContainerProps } from './container.js' +import { ProcessOptions } from './postcss.js' +import Result from './result.js' +import Root from './root.js' + +declare namespace Document { + export interface DocumentProps extends ContainerProps { + nodes?: readonly Root[] + + /** + * Information to generate byte-to-byte equal node string as it was + * in the origin input. + * + * Every parser saves its own properties. + */ + raws?: Record + } + + export { Document_ as default } +} + +/** + * Represents a file and contains all its parsed nodes. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + * + * ```js + * const document = htmlParser( + * '' + * ) + * document.type //=> 'document' + * document.nodes.length //=> 2 + * ``` + */ +declare class Document_ extends Container { + nodes: Root[] + parent: undefined + type: 'document' + + constructor(defaults?: Document.DocumentProps) + + assign(overrides: Document.DocumentProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this + + /** + * Returns a `Result` instance representing the document’s CSS roots. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * const document = postcss.document() + * document.append(root1) + * document.append(root2) + * const result = document.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current document’s CSS. + */ + toResult(options?: ProcessOptions): Result +} + +declare class Document extends Document_ {} + +export = Document diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/document.js b/e-commerce/node_modules/next/node_modules/postcss/lib/document.js new file mode 100644 index 0000000000000000000000000000000000000000..44689917fc57d210b1a4dfad4187ac721c6eb16d --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/document.js @@ -0,0 +1,33 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Document extends Container { + constructor(defaults) { + // type needs to be passed to super, otherwise child roots won't be normalized correctly + super({ type: 'document', ...defaults }) + + if (!this.nodes) { + this.nodes = [] + } + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + + return lazy.stringify() + } +} + +Document.registerLazyResult = dependant => { + LazyResult = dependant +} + +Document.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Document +Document.default = Document diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/fromJSON.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/fromJSON.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a0c5b85fd5c3a755bb07e7da3474a4633023f3a --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/fromJSON.d.ts @@ -0,0 +1,9 @@ +import { JSONHydrator } from './postcss.js' + +interface FromJSON extends JSONHydrator { + default: FromJSON +} + +declare let fromJSON: FromJSON + +export = fromJSON diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/fromJSON.js b/e-commerce/node_modules/next/node_modules/postcss/lib/fromJSON.js new file mode 100644 index 0000000000000000000000000000000000000000..c1a9509b4cc7672c03a5e0ccae03a6d64cf9c15b --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/fromJSON.js @@ -0,0 +1,107 @@ +'use strict' + +let AtRule = require('./at-rule') +let Comment = require('./comment') +let Declaration = require('./declaration') +let Input = require('./input') +let PreviousMap = require('./previous-map') +let Root = require('./root') +let Rule = require('./rule') + +function hydrateInputs(json, inputs) { + if (!json.inputs) return inputs + return json.inputs.map(input => { + let inputHydrated = { ...input, __proto__: Input.prototype } + if (inputHydrated.map) { + inputHydrated.map = { + ...inputHydrated.map, + __proto__: PreviousMap.prototype + } + } + return inputHydrated + }) +} + +function constructNode(json, inputs, children) { + let defaults = { ...json } + delete defaults.inputs + delete defaults.nodes + if (defaults.source) { + let { inputId, ...source } = defaults.source + defaults.source = source + if (inputId != null) { + defaults.source.input = inputs[inputId] + } + } + + let node + if (defaults.type === 'root') { + node = new Root(defaults) + } else if (defaults.type === 'decl') { + node = new Declaration(defaults) + } else if (defaults.type === 'rule') { + node = new Rule(defaults) + } else if (defaults.type === 'comment') { + node = new Comment(defaults) + } else if (defaults.type === 'atrule') { + node = new AtRule(defaults) + } else { + throw new Error('Unknown node type: ' + json.type) + } + + // Rehydrated children are attached after construction. Passing them + // through the container constructor would re-run insertion spacing + // normalization and overwrite each child's own `raws.before`. + if (children) { + node.nodes = children + for (let child of children) child.parent = node + } + + return node +} + +function fromJSON(json, inputs) { + if (Array.isArray(json)) return json.map(n => fromJSON(n)) + + // An explicit stack instead of recursive calls to survive deeply + // nested trees. Children are rehydrated before their parent node + // is constructed. + let result + let stack = [ + { childIndex: 0, children: [], inputs: hydrateInputs(json, inputs), json } + ] + + while (stack.length > 0) { + let frame = stack[stack.length - 1] + let jsonNodes = frame.json.nodes + + if (jsonNodes && frame.childIndex < jsonNodes.length) { + let childJson = jsonNodes[frame.childIndex] + frame.childIndex += 1 + stack.push({ + childIndex: 0, + children: [], + inputs: hydrateInputs(childJson, frame.inputs), + json: childJson + }) + continue + } + + stack.pop() + let node = constructNode( + frame.json, + frame.inputs, + jsonNodes ? frame.children : undefined + ) + if (stack.length > 0) { + stack[stack.length - 1].children.push(node) + } else { + result = node + } + } + + return result +} + +module.exports = fromJSON +fromJSON.default = fromJSON diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/input.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/input.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca2d26bf8444221e2c97eca099209bf4b085e6d8 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/input.d.ts @@ -0,0 +1,226 @@ +import { CssSyntaxError, ProcessOptions } from './postcss.js' +import PreviousMap from './previous-map.js' + +declare namespace Input { + export interface FilePosition { + /** + * Column of inclusive start position in source file. + */ + column: number + + /** + * Column of exclusive end position in source file. + */ + endColumn?: number + + /** + * Line of exclusive end position in source file. + */ + endLine?: number + + /** + * Offset of exclusive end position in source file. + */ + endOffset?: number + + /** + * Absolute path to the source file. + */ + file?: string + + /** + * Line of inclusive start position in source file. + */ + line: number + + /** + * Offset of inclusive start position in source file. + */ + offset: number + + /** + * Source code. + */ + source?: string + + /** + * URL for the source file. + */ + url: string + } + + export { Input_ as default } +} + +/** + * Represents the source CSS. + * + * ```js + * const root = postcss.parse(css, { from: file }) + * const input = root.source.input + * ``` + */ +declare class Input_ { + /** + * Input CSS source. + * + * ```js + * const input = postcss.parse('a{}', { from: file }).input + * input.css //=> "a{}" + * ``` + */ + css: string + + /** + * Input source with support for non-CSS documents. + * + * ```js + * const input = postcss.parse('a{}', { from: file, document: '' }).input + * input.document //=> "" + * input.css //=> "a{}" + * ``` + */ + document: string + + /** + * The absolute path to the CSS source file defined + * with the `from` option. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.file //=> '/home/ai/a.css' + * ``` + */ + file?: string + + /** + * The flag to indicate whether or not the source code has Unicode BOM. + */ + hasBOM: boolean + + /** + * The unique ID of the CSS source. It will be created if `from` option + * is not provided (because PostCSS does not know the file path). + * + * ```js + * const root = postcss.parse(css) + * root.source.input.file //=> undefined + * root.source.input.id //=> "" + * ``` + */ + id?: string + + /** + * The input source map passed from a compilation step before PostCSS + * (for example, from Sass compiler). + * + * ```js + * root.source.input.map.consumer().sources //=> ['a.sass'] + * ``` + */ + map: PreviousMap + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.from //=> "/home/ai/a.css" + * + * const root = postcss.parse(css) + * root.source.input.from //=> "" + * ``` + */ + get from(): string + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * Returns `CssSyntaxError` with information about the error and its position. + */ + error( + message: string, + start: + | { + column: number + line: number + } + | { + offset: number + }, + end: + | { + column: number + line: number + } + | { + offset: number + }, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + error( + message: string, + line: number, + column: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + error( + message: string, + offset: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + /** + * Converts source line and column to offset. + * + * @param line Source line. + * @param column Source column. + * @return Source offset. + */ + fromLineAndColumn(line: number, column: number): number + + /** + * Converts source offset to line and column. + * + * @param offset Source offset. + */ + fromOffset(offset: number): { col: number; line: number } | null + + /** + * Reads the input source map and returns a symbol position + * in the input source (e.g., in a Sass file that was compiled + * to CSS before being passed to PostCSS). Optionally takes an + * end position, exclusive. + * + * ```js + * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } + * root.source.input.origin(1, 1, 1, 4) + * //=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 } + * ``` + * + * @param line Line for inclusive start position in input CSS. + * @param column Column for inclusive start position in input CSS. + * @param endLine Line for exclusive end position in input CSS. + * @param endColumn Column for exclusive end position in input CSS. + * + * @return Position in input source. + */ + origin( + line: number, + column: number, + endLine?: number, + endColumn?: number + ): false | Input.FilePosition + + /** Converts this to a JSON-friendly object representation. */ + toJSON(): object +} + +declare class Input extends Input_ {} + +export = Input diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/input.js b/e-commerce/node_modules/next/node_modules/postcss/lib/input.js new file mode 100644 index 0000000000000000000000000000000000000000..defe395fc633cf7b39af4b3fd4e1a1e7696206f9 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/input.js @@ -0,0 +1,282 @@ +'use strict' + +let { nanoid } = require('nanoid/non-secure') +let { isAbsolute, resolve } = require('path') +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { fileURLToPath, pathToFileURL } = require('url') + +let CssSyntaxError = require('./css-syntax-error') +let PreviousMap = require('./previous-map') +let terminalHighlight = require('./terminal-highlight') + +let lineToIndexCache = Symbol('lineToIndexCache') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(resolve && isAbsolute) + +function getLineToIndex(input) { + if (input[lineToIndexCache]) return input[lineToIndexCache] + let lines = input.css.split('\n') + let lineToIndex = new Array(lines.length) + let prevIndex = 0 + + for (let i = 0, l = lines.length; i < l; i++) { + lineToIndex[i] = prevIndex + prevIndex += lines[i].length + 1 + } + + input[lineToIndexCache] = lineToIndex + return lineToIndex +} + +class Input { + get from() { + return this.file || this.id + } + + constructor(css, opts = {}) { + if ( + css === null || + typeof css === 'undefined' || + (typeof css === 'object' && !css.toString) + ) { + throw new Error(`PostCSS received ${css} instead of CSS string`) + } + + this.css = css.toString() + + if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { + this.hasBOM = true + this.css = this.css.slice(1) + } else { + this.hasBOM = false + } + + this.document = this.css + if (opts.document) this.document = opts.document.toString() + + if (opts.from) { + if ( + !pathAvailable || + /^\w+:\/\//.test(opts.from) || + isAbsolute(opts.from) + ) { + this.file = opts.from + } else { + this.file = resolve(opts.from) + } + } + + if (pathAvailable && sourceMapAvailable) { + let map = new PreviousMap(this.css, opts) + if (map.text) { + this.map = map + let file = map.consumer().file + if (!this.file && file) this.file = this.mapResolve(file) + } + } + + if (!this.file) { + this.id = '' + } + if (this.map) this.map.file = this.from + } + + error(message, line, column, opts = {}) { + let endColumn, endLine, endOffset, offset, result + + if (line && typeof line === 'object') { + let start = line + let end = column + if (typeof start.offset === 'number') { + offset = start.offset + let pos = this.fromOffset(offset) + line = pos.line + column = pos.col + } else { + line = start.line + column = start.column + offset = this.fromLineAndColumn(line, column) + } + if (typeof end.offset === 'number') { + endOffset = end.offset + let pos = this.fromOffset(endOffset) + endLine = pos.line + endColumn = pos.col + } else { + endLine = end.line + endColumn = end.column + endOffset = this.fromLineAndColumn(end.line, end.column) + } + } else if (!column) { + offset = line + let pos = this.fromOffset(offset) + line = pos.line + column = pos.col + } else { + offset = this.fromLineAndColumn(line, column) + } + + let origin = this.origin(line, column, endLine, endColumn) + if (origin) { + result = new CssSyntaxError( + message, + origin.endLine === undefined + ? origin.line + : { column: origin.column, line: origin.line }, + origin.endLine === undefined + ? origin.column + : { column: origin.endColumn, line: origin.endLine }, + origin.source, + origin.file, + opts.plugin + ) + } else { + result = new CssSyntaxError( + message, + endLine === undefined ? line : { column, line }, + endLine === undefined ? column : { column: endColumn, line: endLine }, + this.css, + this.file, + opts.plugin + ) + } + + result.input = { + column, + endColumn, + endLine, + endOffset, + line, + offset, + source: this.css + } + if (this.file) { + if (pathToFileURL) { + result.input.url = pathToFileURL(this.file).toString() + } + result.input.file = this.file + } + + return result + } + + fromLineAndColumn(line, column) { + let lineToIndex = getLineToIndex(this) + let index = lineToIndex[line - 1] + return index + column - 1 + } + + fromOffset(offset) { + let lineToIndex = getLineToIndex(this) + let lastLine = lineToIndex[lineToIndex.length - 1] + + let min = 0 + if (offset >= lastLine) { + min = lineToIndex.length - 1 + } else { + let max = lineToIndex.length - 2 + let mid + while (min < max) { + mid = min + ((max - min) >> 1) + if (offset < lineToIndex[mid]) { + max = mid - 1 + } else if (offset >= lineToIndex[mid + 1]) { + min = mid + 1 + } else { + min = mid + break + } + } + } + return { + col: offset - lineToIndex[min] + 1, + line: min + 1 + } + } + + mapResolve(file) { + if (/^\w+:\/\//.test(file)) { + return file + } + return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) + } + + origin(line, column, endLine, endColumn) { + if (!this.map) return false + let consumer = this.map.consumer() + + let from = consumer.originalPositionFor({ column: column - 1, line }) + if (!from.source) return false + + let to + if (typeof endLine === 'number') { + let toPosition = consumer.originalPositionFor({ + column: endColumn - 1, + line: endLine + }) + // The source map may not have a mapping that covers the end position + // (`originalPositionFor()` then returns `null` for `line`/`column` + // instead of omitting them). Treat that the same as not requesting + // an end position at all, so `endLine`/`endColumn` stay a consistent + // `undefined` pair instead of a mix of `null` and a bogus number. + if (toPosition.source) to = toPosition + } + + let fromUrl + + if (isAbsolute(from.source)) { + fromUrl = pathToFileURL(from.source) + } else { + fromUrl = new URL( + from.source, + this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile) + ) + } + + let result = { + column: from.column + 1, + endColumn: to && to.column + 1, + endLine: to && to.line, + line: from.line, + url: fromUrl.toString() + } + + if (fromUrl.protocol === 'file:') { + if (fileURLToPath) { + result.file = fileURLToPath(fromUrl) + } else { + /* c8 ignore next 2 */ + throw new Error(`file: protocol is not available in this PostCSS build`) + } + } + + let source = consumer.sourceContentFor(from.source) + if (source) result.source = source + + return result + } + + toJSON() { + let json = {} + for (let name of ['hasBOM', 'css', 'file', 'id']) { + if (this[name] != null) { + json[name] = this[name] + } + } + if (this.map) { + json.map = { ...this.map } + if (json.map.consumerCache) { + json.map.consumerCache = undefined + } + } + return json + } +} + +module.exports = Input +Input.default = Input + +if (terminalHighlight && terminalHighlight.registerInput) { + terminalHighlight.registerInput(Input) +} diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/lazy-result.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/lazy-result.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..599a614bf2b6a1e07faf74e8acae3e57273bc628 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/lazy-result.d.ts @@ -0,0 +1,189 @@ +import Document from './document.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Result, { Message, ResultOptions } from './result.js' +import Root from './root.js' +import Warning from './warning.js' + +declare namespace LazyResult { + export { LazyResult_ as default } +} + +/** + * A Promise proxy for the result of PostCSS transformations. + * + * A `LazyResult` instance is returned by `Processor#process`. + * + * ```js + * const lazy = postcss([autoprefixer]).process(css) + * ``` + */ +declare class LazyResult_ implements PromiseLike< + Result +> { + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onRejected for each error thrown in any plugin. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }).catch(error => { + * console.error(error) + * }) + * ``` + */ + catch: Promise>['catch'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onFinally on any error or when all plugins will finish work. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).finally(() => { + * console.log('processing ended') + * }) + * ``` + */ + finally: Promise>['finally'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls `onFulfilled` with a Result instance. If a plugin throws + * an error, the `onRejected` callback will be executed. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => { + * console.log(result.css) + * }) + * ``` + */ + then: Promise>['then'] + + /** + * An alias for the `css` property. Use it with syntaxes + * that generate non-CSS output. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get content(): string + + /** + * Processes input CSS through synchronous plugins, converts `Root` + * to a CSS string and returns `Result#css`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get css(): string + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#map`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get map(): SourceMap + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#messages`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get messages(): Message[] + + /** + * Options from the `Processor#process` call. + */ + get opts(): ResultOptions + + /** + * Returns a `Processor` instance, which will be used + * for CSS transformations. + */ + get processor(): Processor + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#root`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get root(): RootNode + + /** + * Returns the default string description of an object. + * Required to implement the Promise interface. + */ + get [Symbol.toStringTag](): string + + /** + * @param processor Processor used for this transformation. + * @param css CSS to parse and transform. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, css: string, opts: ResultOptions) + + /** + * Run plugin in async way and return `Result`. + * + * @return Result with output content. + */ + async(): Promise> + + /** + * Run plugin in sync way and return `Result`. + * + * @return Result with output content. + */ + sync(): Result + + /** + * Alias for the `LazyResult#css` property. + * + * ```js + * lazy + '' === lazy.css + * ``` + * + * @return Output CSS. + */ + toString(): string + + /** + * Processes input CSS through synchronous plugins + * and calls `Result#warnings`. + * + * @return Warnings from plugins. + */ + warnings(): Warning[] +} + +declare class LazyResult< + RootNode = Document | Root +> extends LazyResult_ {} + +export = LazyResult diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/lazy-result.js b/e-commerce/node_modules/next/node_modules/postcss/lib/lazy-result.js new file mode 100644 index 0000000000000000000000000000000000000000..01b40736ace1690168ca4ebb324111e69651b6c5 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/lazy-result.js @@ -0,0 +1,605 @@ +'use strict' + +let Container = require('./container') +let Document = require('./document') +let MapGenerator = require('./map-generator') +let parse = require('./parse') +let Result = require('./result') +let Root = require('./root') +let stringify = require('./stringify') +let { isClean, my } = require('./symbols') +let warnOnce = require('./warn-once') + +const TYPE_TO_CLASS_NAME = { + atrule: 'AtRule', + comment: 'Comment', + decl: 'Declaration', + document: 'Document', + root: 'Root', + rule: 'Rule' +} + +const PLUGIN_PROPS = { + AtRule: true, + AtRuleExit: true, + Comment: true, + CommentExit: true, + Declaration: true, + DeclarationExit: true, + Document: true, + DocumentExit: true, + Once: true, + OnceExit: true, + postcssPlugin: true, + prepare: true, + Root: true, + RootExit: true, + Rule: true, + RuleExit: true +} + +const NOT_VISITORS = { + Once: true, + postcssPlugin: true, + prepare: true +} + +const CHILDREN = 0 + +function isPromise(obj) { + return typeof obj === 'object' && typeof obj.then === 'function' +} + +function getEvents(node) { + let key = false + let type = TYPE_TO_CLASS_NAME[node.type] + if (node.type === 'decl') { + key = node.prop.toLowerCase() + } else if (node.type === 'atrule') { + key = node.name.toLowerCase() + } + + if (key && node.append) { + return [ + type, + type + '-' + key, + CHILDREN, + type + 'Exit', + type + 'Exit-' + key + ] + } else if (key) { + return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] + } else if (node.append) { + return [type, CHILDREN, type + 'Exit'] + } else { + return [type, type + 'Exit'] + } +} + +function toStack(node) { + let events + if (node.type === 'document') { + events = ['Document', CHILDREN, 'DocumentExit'] + } else if (node.type === 'root') { + events = ['Root', CHILDREN, 'RootExit'] + } else { + events = getEvents(node) + } + + return { + eventIndex: 0, + events, + iterator: 0, + node, + visitorIndex: 0, + visitors: [] + } +} + +function cleanMarks(node) { + let stack = [node] + while (stack.length > 0) { + let next = stack.pop() + next[isClean] = false + if (next.nodes) { + for (let i of next.nodes) stack.push(i) + } + } + return node +} + +let postcss = {} + +class LazyResult { + get content() { + return this.stringify().content + } + + get css() { + return this.stringify().css + } + + get map() { + return this.stringify().map + } + + get messages() { + return this.sync().messages + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + return this.sync().root + } + + get [Symbol.toStringTag]() { + return 'LazyResult' + } + + constructor(processor, css, opts) { + this.stringified = false + this.processed = false + + let root + if ( + typeof css === 'object' && + css !== null && + (css.type === 'root' || css.type === 'document') + ) { + root = cleanMarks(css) + } else if (css instanceof LazyResult || css instanceof Result) { + root = cleanMarks(css.root) + if (css.map) { + if (typeof opts.map === 'undefined') opts.map = {} + if (!opts.map.inline) opts.map.inline = false + opts.map.prev = css.map + } + } else { + let parser = parse + if (opts.syntax) parser = opts.syntax.parse + if (opts.parser) parser = opts.parser + if (parser.parse) parser = parser.parse + + try { + root = parser(css, opts) + } catch (error) { + this.processed = true + this.error = error + } + + if (root && !root[my]) { + /* c8 ignore next 2 */ + Container.rebuild(root) + } + } + + this.result = new Result(processor, root, opts) + this.helpers = { ...postcss, postcss, result: this.result } + this.plugins = this.processor.plugins.map(plugin => { + if (typeof plugin === 'object' && plugin.prepare) { + return { ...plugin, ...plugin.prepare(this.result) } + } else { + return plugin + } + }) + } + + async() { + if (this.error) return Promise.reject(this.error) + if (this.processed) return Promise.resolve(this.result) + if (!this.processing) { + this.processing = this.runAsync() + } + return this.processing + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + getAsyncError() { + throw new Error('Use process(css).then(cb) to work with async plugins') + } + + handleError(error, node) { + let plugin = this.result.lastPlugin + try { + if (node) node.addToError(error) + this.error = error + if (error.name === 'CssSyntaxError' && !error.plugin) { + error.plugin = plugin.postcssPlugin + error.setMessage() + } else if (plugin.postcssVersion) { + if (process.env.NODE_ENV !== 'production') { + let pluginName = plugin.postcssPlugin + let pluginVer = plugin.postcssVersion + let runtimeVer = this.result.processor.version + let a = pluginVer.split('.') + let b = runtimeVer.split('.') + + if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { + // eslint-disable-next-line no-console + console.error( + 'Unknown error from PostCSS plugin. Your current PostCSS ' + + 'version is ' + + runtimeVer + + ', but ' + + pluginName + + ' uses ' + + pluginVer + + '. Perhaps this is the source of the error below.' + ) + } + } + } + } catch (err) { + /* c8 ignore next 3 */ + // eslint-disable-next-line no-console + if (console && console.error) console.error(err) + } + return error + } + + prepareVisitors() { + this.listeners = {} + let add = (plugin, type, cb) => { + if (!this.listeners[type]) this.listeners[type] = [] + this.listeners[type].push([plugin, cb]) + } + for (let plugin of this.plugins) { + if (typeof plugin === 'object') { + for (let event in plugin) { + if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { + throw new Error( + `Unknown event ${event} in ${plugin.postcssPlugin}. ` + + `Try to update PostCSS (${this.processor.version} now).` + ) + } + if (!NOT_VISITORS[event]) { + if (typeof plugin[event] === 'object') { + for (let filter in plugin[event]) { + if (filter === '*') { + add(plugin, event, plugin[event][filter]) + } else { + add( + plugin, + event + '-' + filter.toLowerCase(), + plugin[event][filter] + ) + } + } + } else if (typeof plugin[event] === 'function') { + add(plugin, event, plugin[event]) + } + } + } + } + } + this.hasListener = Object.keys(this.listeners).length > 0 + } + + async runAsync() { + this.plugin = 0 + for (let i = 0; i < this.plugins.length; i++) { + let plugin = this.plugins[i] + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + try { + await promise + } catch (error) { + throw this.handleError(error) + } + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + let stack = [toStack(root)] + while (stack.length > 0) { + let promise = this.visitTick(stack) + if (isPromise(promise)) { + try { + await promise + } catch (e) { + let node = stack[stack.length - 1].node + throw this.handleError(e, node) + } + } + } + } + + if (this.listeners.OnceExit) { + for (let [plugin, visitor] of this.listeners.OnceExit) { + this.result.lastPlugin = plugin + try { + if (root.type === 'document') { + let roots = root.nodes.map(subRoot => + visitor(subRoot, this.helpers) + ) + + await Promise.all(roots) + } else { + await visitor(root, this.helpers) + } + } catch (e) { + throw this.handleError(e) + } + } + } + } + + this.processed = true + return this.stringify() + } + + runOnRoot(plugin) { + this.result.lastPlugin = plugin + try { + if (typeof plugin === 'object' && plugin.Once) { + if (this.result.root.type === 'document') { + let roots = this.result.root.nodes.map(root => + plugin.Once(root, this.helpers) + ) + + if (isPromise(roots[0])) { + return Promise.all(roots) + } + + return roots + } + + return plugin.Once(this.result.root, this.helpers) + } else if (typeof plugin === 'function') { + return plugin(this.result.root, this.result) + } + } catch (error) { + throw this.handleError(error) + } + } + + stringify() { + if (this.error) throw this.error + if (this.stringified) return this.result + this.stringified = true + + this.sync() + + let opts = this.result.opts + let str = stringify + if (opts.syntax) str = opts.syntax.stringify + if (opts.stringifier) str = opts.stringifier + if (str.stringify) str = str.stringify + + let rootSource = this.result.root.source + if ( + opts.map === undefined && + !(rootSource && rootSource.input && rootSource.input.map) + ) { + let result = '' + str(this.result.root, i => { + result += i + }) + this.result.css = result + return this.result + } + + let map = new MapGenerator(str, this.result.root, this.result.opts) + let data = map.generate() + this.result.css = data[0] + this.result.map = data[1] + + return this.result + } + + sync() { + if (this.error) throw this.error + if (this.processed) return this.result + this.processed = true + + if (this.processing) { + throw this.getAsyncError() + } + + for (let plugin of this.plugins) { + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + this.walkSync(root) + } + if (this.listeners.OnceExit) { + if (root.type === 'document') { + for (let subRoot of root.nodes) { + this.visitSync(this.listeners.OnceExit, subRoot) + } + } else { + this.visitSync(this.listeners.OnceExit, root) + } + } + } + + return this.result + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this.opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this.css + } + + visitSync(visitors, node) { + for (let [plugin, visitor] of visitors) { + this.result.lastPlugin = plugin + let promise + try { + promise = visitor(node, this.helpers) + } catch (e) { + throw this.handleError(e, node.proxyOf) + } + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + return true + } + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + } + + visitTick(stack) { + let visit = stack[stack.length - 1] + let { node, visitors } = visit + + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + stack.pop() + return + } + + if (visitors.length > 0 && visit.visitorIndex < visitors.length) { + let [plugin, visitor] = visitors[visit.visitorIndex] + visit.visitorIndex += 1 + if (visit.visitorIndex === visitors.length) { + visit.visitors = [] + visit.visitorIndex = 0 + } + this.result.lastPlugin = plugin + try { + return visitor(node.toProxy(), this.helpers) + } catch (e) { + throw this.handleError(e, node) + } + } + + if (visit.iterator !== 0) { + let iterator = visit.iterator + let child + while ((child = node.nodes[node.indexes[iterator]])) { + node.indexes[iterator] += 1 + if (!child[isClean]) { + child[isClean] = true + stack.push(toStack(child)) + return + } + } + visit.iterator = 0 + delete node.indexes[iterator] + } + + let events = visit.events + while (visit.eventIndex < events.length) { + let event = events[visit.eventIndex] + visit.eventIndex += 1 + if (event === CHILDREN) { + if (node.nodes && node.nodes.length) { + node[isClean] = true + visit.iterator = node.getIterator() + } + return + } else if (this.listeners[event]) { + visit.visitors = this.listeners[event] + return + } + } + stack.pop() + } + + walkSync(node) { + // An explicit stack like in async `visitTick()` to survive deeply + // nested trees. Unlike `visitTick()`, nodes are marked clean only + // on entering, so a node dirtied by its own visitors is revisited + // on the next pass. + node[isClean] = true + let stack = [{ eventIndex: 0, events: getEvents(node), iterator: 0, node }] + + while (stack.length > 0) { + let visit = stack[stack.length - 1] + let visitNode = visit.node + + if (visit.iterator !== 0) { + let iterator = visit.iterator + let child + let descended = false + while ((child = visitNode.nodes[visitNode.indexes[iterator]])) { + visitNode.indexes[iterator] += 1 + if (!child[isClean]) { + child[isClean] = true + stack.push({ + eventIndex: 0, + events: getEvents(child), + iterator: 0, + node: child + }) + descended = true + break + } + } + if (descended) continue + visit.iterator = 0 + delete visitNode.indexes[iterator] + } + + if (visit.eventIndex < visit.events.length) { + let event = visit.events[visit.eventIndex] + visit.eventIndex += 1 + if (event === CHILDREN) { + if (visitNode.nodes && visitNode.nodes.length) { + visit.iterator = visitNode.getIterator() + } + } else { + let visitors = this.listeners[event] + if (visitors) { + if (this.visitSync(visitors, visitNode.toProxy())) stack.pop() + } + } + continue + } + + stack.pop() + } + } + + warnings() { + return this.sync().warnings() + } +} + +LazyResult.registerPostcss = dependant => { + postcss = dependant +} + +module.exports = LazyResult +LazyResult.default = LazyResult + +Root.registerLazyResult(LazyResult) +Document.registerLazyResult(LazyResult) diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/list.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/list.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..119624e8744e125e86959fe33a68e091c256eb0d --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/list.d.ts @@ -0,0 +1,60 @@ +declare namespace list { + type List = { + /** + * Safely splits comma-separated values (such as those for `transition-*` + * and `background` properties). + * + * ```js + * Once (root, { list }) { + * list.comma('black, linear-gradient(white, black)') + * //=> ['black', 'linear-gradient(white, black)'] + * } + * ``` + * + * @param str Comma-separated values. + * @return Split values. + */ + comma(str: string): string[] + + default: List + + /** + * Safely splits space-separated values (such as those for `background`, + * `border-radius`, and other shorthand properties). + * + * ```js + * Once (root, { list }) { + * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param str Space-separated values. + * @return Split values. + */ + space(str: string): string[] + + /** + * Safely splits values. + * + * ```js + * Once (root, { list }) { + * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param string separated values. + * @param separators array of separators. + * @param last boolean indicator. + * @return Split values. + */ + split( + string: string, + separators: readonly string[], + last: boolean + ): string[] + } +} + +declare let list: list.List + +export = list diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/list.js b/e-commerce/node_modules/next/node_modules/postcss/lib/list.js new file mode 100644 index 0000000000000000000000000000000000000000..1b31f9809f2cc41616cc9527e7f601d256e669f8 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/list.js @@ -0,0 +1,58 @@ +'use strict' + +let list = { + comma(string) { + return list.split(string, [','], true) + }, + + space(string) { + let spaces = [' ', '\n', '\t'] + return list.split(string, spaces) + }, + + split(string, separators, last) { + let array = [] + let current = '' + let split = false + + let func = 0 + let inQuote = false + let prevQuote = '' + let escape = false + + for (let letter of string) { + if (escape) { + escape = false + } else if (letter === '\\') { + escape = true + } else if (inQuote) { + if (letter === prevQuote) { + inQuote = false + } + } else if (letter === '"' || letter === "'") { + inQuote = true + prevQuote = letter + } else if (letter === '(') { + func += 1 + } else if (letter === ')') { + if (func > 0) func -= 1 + } else if (func === 0) { + if (separators.includes(letter)) split = true + } + + if (split) { + if (current !== '') array.push(current.trim()) + current = '' + split = false + } else { + current += letter + } + } + + if (last || current !== '') array.push(current.trim()) + return array + } +} + +module.exports = list +list.default = list diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/map-generator.js b/e-commerce/node_modules/next/node_modules/postcss/lib/map-generator.js new file mode 100644 index 0000000000000000000000000000000000000000..df880ac99f7dc35f2779e7994d09c5f9f578e26c --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/map-generator.js @@ -0,0 +1,376 @@ +'use strict' + +let { dirname, relative, resolve, sep } = require('path') +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { pathToFileURL } = require('url') + +let Input = require('./input') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(dirname && resolve && relative && sep) + +class MapGenerator { + constructor(stringify, root, opts, cssString) { + this.stringify = stringify + this.mapOpts = opts.map || {} + this.root = root + this.opts = opts + this.css = cssString + this.originalCSS = cssString + this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute + + this.memoizedFileURLs = new Map() + this.memoizedPaths = new Map() + this.memoizedURLs = new Map() + } + + addAnnotation() { + let content + + if (this.isInline()) { + content = + 'data:application/json;base64,' + this.toBase64(this.map.toString()) + } else if (typeof this.mapOpts.annotation === 'string') { + content = this.mapOpts.annotation + } else if (typeof this.mapOpts.annotation === 'function') { + content = this.mapOpts.annotation(this.opts.to, this.root) + } else { + content = this.outputFile() + '.map' + } + let eol = '\n' + if (this.css.includes('\r\n')) eol = '\r\n' + + this.css += eol + '/*# sourceMappingURL=' + content + ' */' + } + + applyPrevMaps() { + for (let prev of this.previous()) { + let from = this.toUrl(this.path(prev.file)) + let root = prev.root || dirname(prev.file) + let map + + if (this.mapOpts.sourcesContent === false) { + map = new SourceMapConsumer(prev.text) + if (map.sourcesContent) { + map.sourcesContent = null + } + } else { + map = prev.consumer() + } + + this.map.applySourceMap(map, from, this.toUrl(this.path(root))) + } + } + + clearAnnotation() { + if (this.mapOpts.annotation === false) return + + if (this.root) { + let node + for (let i = this.root.nodes.length - 1; i >= 0; i--) { + node = this.root.nodes[i] + if (node.type !== 'comment') continue + if (node.text.startsWith('# sourceMappingURL=')) { + this.root.removeChild(i) + } + } + } else if (this.css) { + let startIndex + while ((startIndex = this.css.lastIndexOf('/*#')) !== -1) { + let endIndex = this.css.indexOf('*/', startIndex + 3) + if (endIndex === -1) break + while (startIndex > 0 && this.css[startIndex - 1] === '\n') { + startIndex-- + } + this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2) + } + } + } + + generate() { + this.clearAnnotation() + if (pathAvailable && sourceMapAvailable && this.isMap()) { + return this.generateMap() + } else { + let result = '' + this.stringify(this.root, i => { + result += i + }) + return [result] + } + } + + generateMap() { + if (this.root) { + this.generateString() + } else if (this.previous().length === 1) { + let prev = this.previous()[0].consumer() + prev.file = this.outputFile() + this.map = SourceMapGenerator.fromSourceMap(prev, { + ignoreInvalidMapping: true + }) + } else { + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) + this.map.addMapping({ + generated: { column: 0, line: 1 }, + original: { column: 0, line: 1 }, + source: this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + }) + } + + if (this.isSourcesContent()) this.setSourcesContent() + if (this.root && this.previous().length > 0) this.applyPrevMaps() + if (this.isAnnotation()) this.addAnnotation() + + if (this.isInline()) { + return [this.css] + } else { + return [this.css, this.map] + } + } + + generateString() { + this.css = '' + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) + + let line = 1 + let column = 1 + + let noSource = '' + let mapping = { + generated: { column: 0, line: 0 }, + original: { column: 0, line: 0 }, + source: '' + } + + let last, lines + this.stringify(this.root, (str, node, type) => { + this.css += str + + if (node && type !== 'end') { + mapping.generated.line = line + mapping.generated.column = column - 1 + if (node.source && node.source.start) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.start.line + mapping.original.column = node.source.start.column - 1 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + this.map.addMapping(mapping) + } + } + + lines = str.match(/\n/g) + if (lines) { + line += lines.length + last = str.lastIndexOf('\n') + column = str.length - last + } else { + column += str.length + } + + if (node && type !== 'start') { + let p = node.parent || { raws: {} } + let childless = + node.type === 'decl' || (node.type === 'atrule' && !node.nodes) + if (!childless || node !== p.last || p.raws.semicolon) { + if (node.source && node.source.end) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.end.line + mapping.original.column = node.source.end.column - 1 + mapping.generated.line = line + mapping.generated.column = column - 2 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + mapping.generated.line = line + mapping.generated.column = column - 1 + this.map.addMapping(mapping) + } + } + } + }) + } + + isAnnotation() { + if (this.isInline()) { + return true + } + if (typeof this.mapOpts.annotation !== 'undefined') { + return this.mapOpts.annotation + } + if (this.previous().length) { + return this.previous().some(i => i.annotation) + } + return true + } + + isInline() { + if (typeof this.mapOpts.inline !== 'undefined') { + return this.mapOpts.inline + } + + let annotation = this.mapOpts.annotation + if (typeof annotation !== 'undefined' && annotation !== true) { + return false + } + + if (this.previous().length) { + return this.previous().some(i => i.inline) + } + return true + } + + isMap() { + if (typeof this.opts.map !== 'undefined') { + return !!this.opts.map + } + return this.previous().length > 0 + } + + isSourcesContent() { + if (typeof this.mapOpts.sourcesContent !== 'undefined') { + return this.mapOpts.sourcesContent + } + if (this.previous().length) { + return this.previous().some(i => i.withContent()) + } + return true + } + + outputFile() { + if (this.opts.to) { + return this.path(this.opts.to) + } else if (this.opts.from) { + return this.path(this.opts.from) + } else { + return 'to.css' + } + } + + path(file) { + if (this.mapOpts.absolute) return file + if (file.charCodeAt(0) === 60 /* `<` */) return file + if (/^\w+:\/\//.test(file)) return file + let cached = this.memoizedPaths.get(file) + if (cached) return cached + + let from = this.opts.to ? dirname(this.opts.to) : '.' + + if (typeof this.mapOpts.annotation === 'string') { + from = dirname(resolve(from, this.mapOpts.annotation)) + } + + let path = relative(from, file) + this.memoizedPaths.set(file, path) + + return path + } + + previous() { + if (!this.previousMaps) { + this.previousMaps = [] + if (this.root) { + this.root.walk(node => { + if (node.source && node.source.input.map) { + let map = node.source.input.map + if (!this.previousMaps.includes(map)) { + this.previousMaps.push(map) + } + } + }) + } else { + let input = new Input(this.originalCSS, this.opts) + if (input.map) this.previousMaps.push(input.map) + } + } + + return this.previousMaps + } + + setSourcesContent() { + let already = {} + if (this.root) { + this.root.walk(node => { + if (node.source) { + let from = node.source.input.from + if (from && !already[from]) { + already[from] = true + let fromUrl = this.usesFileUrls + ? this.toFileUrl(from) + : this.toUrl(this.path(from)) + this.map.setSourceContent(fromUrl, node.source.input.css) + } + } + }) + } else if (this.css) { + let from = this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + this.map.setSourceContent(from, this.css) + } + } + + sourcePath(node) { + if (this.mapOpts.from) { + return this.toUrl(this.mapOpts.from) + } else if (this.usesFileUrls) { + return this.toFileUrl(node.source.input.from) + } else { + return this.toUrl(this.path(node.source.input.from)) + } + } + + toBase64(str) { + if (Buffer) { + return Buffer.from(str).toString('base64') + } else { + return window.btoa(unescape(encodeURIComponent(str))) + } + } + + toFileUrl(path) { + let cached = this.memoizedFileURLs.get(path) + if (cached) return cached + + if (pathToFileURL) { + let fileURL = pathToFileURL(path).toString() + this.memoizedFileURLs.set(path, fileURL) + + return fileURL + } else { + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } + + toUrl(path) { + let cached = this.memoizedURLs.get(path) + if (cached) return cached + + if (sep === '\\') { + path = path.replace(/\\/g, '/') + } + + let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent) + this.memoizedURLs.set(path, url) + + return url + } +} + +module.exports = MapGenerator diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/no-work-result.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/no-work-result.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa9d284849af11b0e125430416f35a5738ce52dd --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/no-work-result.d.ts @@ -0,0 +1,45 @@ +import LazyResult from './lazy-result.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Result, { Message, ResultOptions } from './result.js' +import Root from './root.js' +import Warning from './warning.js' + +declare namespace NoWorkResult { + export { NoWorkResult_ as default } +} + +/** + * A Promise proxy for the result of PostCSS transformations. + * This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root` + * are accessed. See the example below for details. + * A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined. + * + * ```js + * const noWorkResult = postcss().process(css) // No plugins are defined. + * // CSS is not parsed + * let root = noWorkResult.root // now css is parsed because we accessed the root + * ``` + */ +declare class NoWorkResult_ implements LazyResult { + catch: Promise>['catch'] + finally: Promise>['finally'] + then: Promise>['then'] + get content(): string + get css(): string + get map(): SourceMap + get messages(): Message[] + get opts(): ResultOptions + get processor(): Processor + get root(): Root + get [Symbol.toStringTag](): string + constructor(processor: Processor, css: string, opts: ResultOptions) + async(): Promise> + sync(): Result + toString(): string + warnings(): Warning[] +} + +declare class NoWorkResult extends NoWorkResult_ {} + +export = NoWorkResult diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/no-work-result.js b/e-commerce/node_modules/next/node_modules/postcss/lib/no-work-result.js new file mode 100644 index 0000000000000000000000000000000000000000..7ec1a7425a8bdaffa9ed912ae8c1c72588158248 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/no-work-result.js @@ -0,0 +1,137 @@ +'use strict' + +let MapGenerator = require('./map-generator') +let parse = require('./parse') +let Result = require('./result') +let stringify = require('./stringify') +let warnOnce = require('./warn-once') + +class NoWorkResult { + get content() { + return this.result.css + } + + get css() { + return this.result.css + } + + get map() { + return this.result.map + } + + get messages() { + return [] + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + if (this._root) { + return this._root + } + + let root + let parser = parse + + try { + root = parser(this._css, this._opts) + } catch (error) { + this.error = error + } + + if (this.error) { + throw this.error + } else { + this._root = root + return root + } + } + + get [Symbol.toStringTag]() { + return 'NoWorkResult' + } + + constructor(processor, css, opts) { + css = css.toString() + this.stringified = false + + this._processor = processor + this._css = css + this._opts = opts + this._map = undefined + + let str = stringify + this.result = new Result(this._processor, undefined, this._opts) + this.result.css = css + + let self = this + Object.defineProperty(this.result, 'root', { + get() { + return self.root + } + }) + + let map = new MapGenerator(str, undefined, this._opts, css) + if (map.isMap()) { + let [generatedCSS, generatedMap] = map.generate() + if (generatedCSS) { + this.result.css = generatedCSS + } + if (generatedMap) { + this.result.map = generatedMap + } + } else { + map.clearAnnotation() + this.result.css = map.css + } + } + + async() { + if (this.error) return Promise.reject(this.error) + return Promise.resolve(this.result) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + sync() { + if (this.error) throw this.error + return this.result + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this._opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this._css + } + + warnings() { + return [] + } +} + +module.exports = NoWorkResult +NoWorkResult.default = NoWorkResult diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/node.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e93ce5baeec9cb20485c262aa9b23a7e0bf109da --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/node.d.ts @@ -0,0 +1,555 @@ +import AtRule = require('./at-rule.js') +import { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container, { NewChild } from './container.js' +import CssSyntaxError from './css-syntax-error.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Document from './document.js' +import Input from './input.js' +import { Stringifier, Syntax } from './postcss.js' +import Result from './result.js' +import Root from './root.js' +import Rule, { RuleProps } from './rule.js' +import Warning, { WarningOptions } from './warning.js' + +declare namespace Node { + export type ChildNode = AtRule.default | Comment | Declaration | Rule + + export type AnyNode = + | AtRule.default + | Comment + | Declaration + | Document + | Root + | Rule + + export type ChildProps = + | AtRuleProps + | CommentProps + | DeclarationProps + | RuleProps + + export interface Position { + /** + * Source column in file. It starts from 1. + */ + column: number + + /** + * Source line in file. It starts from 1. + */ + line: number + + /** + * Source offset in file. It starts from 0. + */ + offset: number + } + + export interface Range { + /** + * End position, exclusive. + */ + end: Position + + /** + * Start position, inclusive. + */ + start: Position + } + + /** + * Source represents an interface for the {@link Node.source} property. + */ + export interface Source { + /** + * The inclusive ending position for the source + * code of a node. + * + * However, `end.offset` of a non `Root` node is the exclusive position. + * See https://github.com/postcss/postcss/pull/1879 for details. + * + * ```js + * const root = postcss.parse('a { color: black }') + * const a = root.first + * const color = a.first + * + * // The offset of `Root` node is the inclusive position + * css.source.end // { line: 1, column: 19, offset: 18 } + * + * // The offset of non `Root` node is the exclusive position + * a.source.end // { line: 1, column: 18, offset: 18 } + * color.source.end // { line: 1, column: 16, offset: 16 } + * ``` + */ + end?: Position + + /** + * The source file from where a node has originated. + */ + input: Input + + /** + * The inclusive starting position for the source + * code of a node. + */ + start?: Position + } + + /** + * Interface represents an interface for an object received + * as parameter by Node class constructor. + */ + export interface NodeProps { + source?: Source + } + + export interface NodeErrorOptions { + /** + * An ending index inside a node's string that should be highlighted as + * source of error. + */ + endIndex?: number + /** + * An index inside a node's string that should be highlighted as source + * of error. + */ + index?: number + /** + * Plugin name that created this error. PostCSS will set it automatically. + */ + plugin?: string + /** + * A word inside a node's string, that should be highlighted as source + * of error. + */ + word?: string + } + + class Node extends Node_ {} + export { Node as default } +} + +/** + * It represents an abstract class that handles common + * methods for other CSS abstract syntax tree nodes. + * + * Any node that represents CSS selector or value should + * not extend the `Node` class. + */ +declare abstract class Node_ { + /** + * It represents parent of the current node. + * + * ```js + * root.nodes[0].parent === root //=> true + * ``` + */ + parent: Container | Document | undefined + + /** + * It represents unnecessary whitespace and characters present + * in the css source code. + * + * Information to generate byte-to-byte equal node string as it was + * in the origin input. + * + * The properties of the raws object are decided by parser, + * the default parser uses the following properties: + * + * * `before`: the space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + * * `after`: the space symbols after the last child of the node + * to the end of the node. + * * `between`: the symbols between the property and value + * for declarations, selector and `{` for rules, or last parameter + * and `{` for at-rules. + * * `semicolon`: contains true if the last child has + * an (optional) semicolon. + * * `afterName`: the space between the at-rule name and its parameters. + * * `left`: the space symbols between `/*` and the comment’s text. + * * `right`: the space symbols between the comment’s text + * and */. + * - `important`: the content of the important statement, + * if it is not just `!important`. + * + * PostCSS filters out the comments inside selectors, declaration values + * and at-rule parameters but it stores the origin content in raws. + * + * ```js + * const root = postcss.parse('a {\n color:black\n}') + * root.first.first.raws //=> { before: '\n ', between: ':' } + * ``` + */ + raws: any + + /** + * It represents information related to origin of a node and is required + * for generating source maps. + * + * The nodes that are created manually using the public APIs + * provided by PostCSS will have `source` undefined and + * will be absent in the source map. + * + * For this reason, the plugin developer should consider + * duplicating nodes as the duplicate node will have the + * same source as the original node by default or assign + * source to a node created manually. + * + * ```js + * decl.source.input.from //=> '/home/ai/source.css' + * decl.source.start //=> { line: 10, column: 2 } + * decl.source.end //=> { line: 10, column: 12 } + * ``` + * + * ```js + * // Incorrect method, source not specified! + * const prefixed = postcss.decl({ + * prop: '-moz-' + decl.prop, + * value: decl.value + * }) + * + * // Correct method, source is inherited when duplicating. + * const prefixed = decl.clone({ + * prop: '-moz-' + decl.prop + * }) + * ``` + * + * ```js + * if (atrule.name === 'add-link') { + * const rule = postcss.rule({ + * selector: 'a', + * source: atrule.source + * }) + * + * atrule.parent.insertBefore(atrule, rule) + * } + * ``` + */ + source?: Node.Source + + /** + * It represents type of a node in + * an abstract syntax tree. + * + * A type of node helps in identification of a node + * and perform operation based on it's type. + * + * ```js + * const declaration = new Declaration({ + * prop: 'color', + * value: 'black' + * }) + * + * declaration.type //=> 'decl' + * ``` + */ + type: string + + constructor(defaults?: object) + + /** + * Insert new node after current node to current node’s parent. + * + * Just alias for `node.parent.insertAfter(node, add)`. + * + * ```js + * decl.after('color: black') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + after( + newNode: Node | Node.ChildProps | readonly Node[] | string | undefined + ): this + + /** + * It assigns properties to an existing node instance. + * + * ```js + * decl.assign({ prop: 'word-wrap', value: 'break-word' }) + * ``` + * + * @param overrides New properties to override the node. + * + * @return `this` for method chaining. + */ + assign(overrides: object): this + + /** + * Insert new node before current node to current node’s parent. + * + * Just alias for `node.parent.insertBefore(node, add)`. + * + * ```js + * decl.before('content: ""') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + before( + newNode: Node | Node.ChildProps | readonly Node[] | string | undefined + ): this + + /** + * Clear the code style properties for the node and its children. + * + * ```js + * node.raws.before //=> ' ' + * node.cleanRaws() + * node.raws.before //=> undefined + * ``` + * + * @param keepBetween Keep the `raws.between` symbols. + */ + cleanRaws(keepBetween?: boolean): void + + /** + * It creates clone of an existing node, which includes all the properties + * and their values, that includes `raws` but not `type`. + * + * ```js + * decl.raws.before //=> "\n " + * const cloned = decl.clone({ prop: '-moz-' + decl.prop }) + * cloned.raws.before //=> "\n " + * cloned.toString() //=> -moz-transform: scale(0) + * ``` + * + * @param overrides New properties to override in the clone. + * + * @return Duplicate of the node instance. + */ + clone(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * after the current node. + * + * @param overrides New properties to override in the clone. + * @return New node. + */ + cloneAfter(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * before the current node. + * + * ```js + * decl.cloneBefore({ prop: '-moz-' + decl.prop }) + * ``` + * + * @param overrides Mew properties to override in the clone. + * + * @return New node + */ + cloneBefore(overrides?: object): this + + /** + * It creates an instance of the class `CssSyntaxError` and parameters passed + * to this method are assigned to the error instance. + * + * The error instance will have description for the + * error, original position of the node in the + * source, showing line and column number. + * + * If any previous map is present, it would be used + * to get original position of the source. + * + * The Previous Map here is referred to the source map + * generated by previous compilation, example: Less, + * Stylus and Sass. + * + * This method returns the error instance instead of + * throwing it. + * + * ```js + * if (!variables[name]) { + * throw decl.error(`Unknown variable ${name}`, { word: name }) + * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + * // color: $black + * // a + * // ^ + * // background: white + * } + * ``` + * + * @param message Description for the error instance. + * @param options Options for the error instance. + * + * @return Error instance is returned. + */ + error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError + + /** + * Returns the next child of the node’s parent. + * Returns `undefined` if the current node is the last child. + * + * ```js + * if (comment.text === 'delete next') { + * const next = comment.next() + * if (next) { + * next.remove() + * } + * } + * ``` + * + * @return Next node. + */ + next(): Node.ChildNode | undefined + + /** + * Get the position for a word or an index inside the node. + * + * @param opts Options. + * @return Position. + */ + positionBy(opts?: Pick): Node.Position + + /** + * Convert string index to line/column. + * + * @param index The symbol number in the node’s string. + * @return Symbol position in file. + */ + positionInside(index: number): Node.Position + + /** + * Returns the previous child of the node’s parent. + * Returns `undefined` if the current node is the first child. + * + * ```js + * const annotation = decl.prev() + * if (annotation.type === 'comment') { + * readAnnotation(annotation.text) + * } + * ``` + * + * @return Previous node. + */ + prev(): Node.ChildNode | undefined + + /** + * Get the range for a word or start and end index inside the node. + * The start index is inclusive; the end index is exclusive. + * + * @param opts Options. + * @return Range. + */ + rangeBy( + opts?: Pick + ): Node.Range + + /** + * Returns a `raws` value. If the node is missing + * the code style property (because the node was manually built or cloned), + * PostCSS will try to autodetect the code style property by looking + * at other nodes in the tree. + * + * ```js + * const root = postcss.parse('a { background: white }') + * root.nodes[0].append({ prop: 'color', value: 'black' }) + * root.nodes[0].nodes[1].raws.before //=> undefined + * root.nodes[0].nodes[1].raw('before') //=> ' ' + * ``` + * + * @param prop Name of code style property. + * @param defaultType Name of default value, it can be missed + * if the value is the same as prop. + * @return {string} Code style value. + */ + raw(prop: string, defaultType?: string): string + + /** + * It removes the node from its parent and deletes its parent property. + * + * ```js + * if (decl.prop.match(/^-webkit-/)) { + * decl.remove() + * } + * ``` + * + * @return `this` for method chaining. + */ + remove(): this + + /** + * Inserts node(s) before the current node and removes the current node. + * + * ```js + * AtRule: { + * mixin: atrule => { + * atrule.replaceWith(mixinRules[atrule.params]) + * } + * } + * ``` + * + * @param nodes Mode(s) to replace current one. + * @return Current node to methods chain. + */ + replaceWith(...nodes: NewChild[]): this + + /** + * Finds the Root instance of the node’s tree. + * + * ```js + * root.nodes[0].nodes[0].root() === root + * ``` + * + * @return Root parent. + */ + root(): Root + + /** + * Fix circular links on `JSON.stringify()`. + * + * @return Cleaned object. + */ + toJSON(): object + + /** + * It compiles the node to browser readable cascading style sheets string + * depending on it's type. + * + * ```js + * new Rule({ selector: 'a' }).toString() //=> "a {}" + * ``` + * + * @param stringifier A syntax to use in string generation. + * @return CSS string of this node. + */ + toString(stringifier?: Stringifier | Syntax): string + + /** + * It is a wrapper for {@link Result#warn}, providing convenient + * way of generating warnings. + * + * ```js + * Declaration: { + * bad: (decl, { result }) => { + * decl.warn(result, 'Deprecated property: bad') + * } + * } + * ``` + * + * @param result The `Result` instance that will receive the warning. + * @param message Description for the warning. + * @param options Options for the warning. + * + * @return `Warning` instance is returned + */ + warn(result: Result, message: string, options?: WarningOptions): Warning + + /** + * If this node isn't already dirty, marks it and its ancestors as such. This + * indicates to the LazyResult processor that the {@link Root} has been + * modified by the current plugin and may need to be processed again by other + * plugins. + */ + protected markDirty(): void +} + +declare class Node extends Node_ {} + +export = Node diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/node.js b/e-commerce/node_modules/next/node_modules/postcss/lib/node.js new file mode 100644 index 0000000000000000000000000000000000000000..a298d3656208cb6dd683b3fda38304b256f7a170 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/node.js @@ -0,0 +1,494 @@ +'use strict' + +let CssSyntaxError = require('./css-syntax-error') +let Stringifier = require('./stringifier') +let stringify = require('./stringify') +let { isClean, my } = require('./symbols') + +function cloneNode(obj, parent) { + let cloned = new obj.constructor() + // An explicit stack instead of recursive calls to survive deeply + // nested trees. Each entry is [source, its clone, clone's parent]. + let stack = [[obj, cloned, parent]] + + while (stack.length > 0) { + let [source, target, targetParent] = stack.pop() + for (let i in source) { + if (!Object.prototype.hasOwnProperty.call(source, i)) { + /* c8 ignore next 2 */ + continue + } + if (i === 'proxyCache') continue + let value = source[i] + let type = typeof value + + if (i === 'parent' && type === 'object') { + if (targetParent) target[i] = targetParent + } else if (i === 'source') { + target[i] = value + } else if (Array.isArray(value)) { + let children = [] + target[i] = children + for (let j of value) { + let childClone = new j.constructor() + children.push(childClone) + stack.push([j, childClone, target]) + } + } else { + if (type === 'object' && value !== null) { + let valueClone = new value.constructor() + stack.push([value, valueClone, undefined]) + value = valueClone + } + target[i] = value + } + } + } + + return cloned +} + +function sourceOffset(inputCSS, position) { + // Not all custom syntaxes support `offset` in `source.start` and `source.end` + if (position && typeof position.offset !== 'undefined') { + return position.offset + } + + let column = 1 + let line = 1 + let offset = 0 + + for (let i = 0; i < inputCSS.length; i++) { + if (line === position.line && column === position.column) { + offset = i + break + } + + if (inputCSS[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return offset +} + +class Node { + get proxyOf() { + return this + } + + constructor(defaults = {}) { + this.raws = {} + this[isClean] = false + this[my] = true + + for (let name of Object.keys(defaults)) { + if (name === '__proto__') continue + if (name === 'nodes') { + this.nodes = [] + for (let node of defaults[name]) { + // Clone only nodes that already belong to another tree, so passing a + // freshly created (parent-less) node adopts that instance instead of + // a copy and keeps the caller's reference usable. See #1987. + if (typeof node.clone === 'function' && node.parent) { + this.append(node.clone()) + } else { + this.append(node) + } + } + } else { + this[name] = defaults[name] + } + } + } + + addToError(error) { + error.postcssNode = this + if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { + let s = this.source + error.stack = error.stack.replace( + /\n\s{4}at /, + `$&${s.input.from}:${s.start.line}:${s.start.column}$&` + ) + } + return error + } + + after(add) { + this.parent.insertAfter(this, add) + return this + } + + assign(overrides = {}) { + for (let name in overrides) { + this[name] = overrides[name] + } + return this + } + + before(add) { + this.parent.insertBefore(this, add) + return this + } + + cleanRaws(keepBetween) { + delete this.raws.before + delete this.raws.after + if (!keepBetween) delete this.raws.between + } + + clone(overrides = {}) { + let cloned = cloneNode(this) + for (let name in overrides) { + cloned[name] = overrides[name] + } + return cloned + } + + cloneAfter(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertAfter(this, cloned) + return cloned + } + + cloneBefore(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertBefore(this, cloned) + return cloned + } + + error(message, opts = {}) { + if (this.source) { + let { end, start } = this.rangeBy(opts) + return this.source.input.error( + message, + { column: start.column, line: start.line }, + { column: end.column, line: end.line }, + opts + ) + } + return new CssSyntaxError(message) + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (prop === 'root') { + return () => node.root().toProxy() + } else { + return node[prop] + } + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if ( + prop === 'prop' || + prop === 'value' || + prop === 'name' || + prop === 'params' || + prop === 'important' || + /* c8 ignore next */ + prop === 'text' + ) { + node.markDirty() + } + return true + } + } + } + + /* c8 ignore next 3 */ + markClean() { + this[isClean] = true + } + + markDirty() { + if (this[isClean]) { + this[isClean] = false + let next = this + while ((next = next.parent)) { + next[isClean] = false + } + } + } + + next() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index + 1] + } + + positionBy(opts = {}) { + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let pos = { + column: this.source.start.column, + line: this.source.start.line, + offset: sourceOffset(inputString, this.source.start) + } + if (opts.index) { + pos = this.positionInside(opts.index) + } else if (opts.word) { + let stringRepresentation = inputString.slice( + sourceOffset(inputString, this.source.start), + sourceOffset(inputString, this.source.end) + ) + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) pos = this.positionInside(index) + } + return pos + } + + positionInside(index) { + let column = this.source.start.column + let line = this.source.start.line + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let offset = sourceOffset(inputString, this.source.start) + let end = offset + index + + for (let i = offset; i < end; i++) { + if (inputString[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return { column, line, offset: end } + } + + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index - 1] + } + + rangeBy(opts = {}) { + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let start = { + column: this.source.start.column, + line: this.source.start.line, + offset: sourceOffset(inputString, this.source.start) + } + let end = this.source.end + ? { + column: this.source.end.column + 1, + line: this.source.end.line, + offset: + typeof this.source.end.offset === 'number' + ? // `source.end.offset` is exclusive, so we don't need to add 1 + this.source.end.offset + : // Since line/column in this.source.end is inclusive, + // the `sourceOffset(... , this.source.end)` returns an inclusive offset. + // So, we add 1 to convert it to exclusive. + sourceOffset(inputString, this.source.end) + 1 + } + : { + column: start.column + 1, + line: start.line, + offset: start.offset + 1 + } + + if (opts.word) { + let stringRepresentation = inputString.slice( + sourceOffset(inputString, this.source.start), + sourceOffset(inputString, this.source.end) + ) + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) { + start = this.positionInside(index) + end = this.positionInside(index + opts.word.length) + } + } else { + if (opts.start) { + start = { + column: opts.start.column, + line: opts.start.line, + offset: sourceOffset(inputString, opts.start) + } + } else if (typeof opts.index === 'number') { + start = this.positionInside(opts.index) + } + + if (opts.end) { + end = { + column: opts.end.column, + line: opts.end.line, + offset: sourceOffset(inputString, opts.end) + } + } else if (typeof opts.endIndex === 'number') { + end = this.positionInside(opts.endIndex) + } else if (typeof opts.index === 'number') { + end = this.positionInside(opts.index + 1) + } + } + + if ( + end.line < start.line || + (end.line === start.line && end.column <= start.column) + ) { + end = { + column: start.column + 1, + line: start.line, + offset: start.offset + 1 + } + } + + return { end, start } + } + + raw(prop, defaultType) { + let str = new Stringifier() + return str.raw(this, prop, defaultType) + } + + remove() { + if (this.parent) { + this.parent.removeChild(this) + } + this.parent = undefined + return this + } + + replaceWith(...nodes) { + if (this.parent) { + let bookmark = this + let foundSelf = false + for (let node of nodes) { + if (node === this) { + foundSelf = true + } else if (foundSelf) { + this.parent.insertAfter(bookmark, node) + bookmark = node + } else { + this.parent.insertBefore(bookmark, node) + } + } + + if (!foundSelf) { + this.remove() + } + } + + return this + } + + root() { + let result = this + while (result.parent && result.parent.type !== 'document') { + result = result.parent + } + return result + } + + toJSON(_, inputs) { + let emitInputs = inputs == null + inputs = inputs || new Map() + + // A worklist instead of recursive `toJSON()` calls to survive deeply + // nested trees. Each entry converts one node and writes the result + // into the already converted parent by [holder, key]. + let holderOfRoot = [] + let queue = [[this, holderOfRoot, 0]] + + for (let step = 0; step < queue.length; step++) { + let [node, holder, key] = queue[step] + let fixed = {} + holder[key] = fixed + + for (let name in node) { + if (!Object.prototype.hasOwnProperty.call(node, name)) { + /* c8 ignore next 2 */ + continue + } + if (name === 'parent' || name === 'proxyCache') continue + let value = node[name] + + if (Array.isArray(value)) { + let fixedArray = [] + fixed[name] = fixedArray + for (let i = 0; i < value.length; i++) { + let item = value[i] + if (typeof item === 'object' && item.toJSON) { + if (item.toJSON === Node.prototype.toJSON) { + queue.push([item, fixedArray, i]) + } else { + fixedArray[i] = item.toJSON(null, inputs) + } + } else { + fixedArray[i] = item + } + } + } else if (typeof value === 'object' && value.toJSON) { + if (value.toJSON === Node.prototype.toJSON) { + queue.push([value, fixed, name]) + } else { + fixed[name] = value.toJSON(null, inputs) + } + } else if (name === 'source') { + if (value == null) continue + let inputId = inputs.get(value.input) + if (inputId == null) { + inputId = inputs.size + inputs.set(value.input, inputId) + } + fixed[name] = { + end: value.end, + inputId, + start: value.start + } + } else { + fixed[name] = value + } + } + } + + let fixed = holderOfRoot[0] + if (emitInputs) { + fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) + } + + return fixed + } + + toProxy() { + if (!this.proxyCache) { + this.proxyCache = new Proxy(this, this.getProxyProcessor()) + } + return this.proxyCache + } + + toString(stringifier = stringify) { + if (stringifier.stringify) stringifier = stringifier.stringify + let result = '' + stringifier(this, i => { + result += i + }) + return result + } + + warn(result, text, opts = {}) { + let data = { node: this } + for (let i in opts) data[i] = opts[i] + return result.warn(text, data) + } +} + +module.exports = Node +Node.default = Node diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/parse.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/parse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffe35b4390997ea1487104d6377630f9c8b5a197 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/parse.d.ts @@ -0,0 +1,9 @@ +import { Parser } from './postcss.js' + +interface Parse extends Parser { + default: Parse +} + +declare let parse: Parse + +export = parse diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/parse.js b/e-commerce/node_modules/next/node_modules/postcss/lib/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..00a1037aa6096bb36ad20b26aeb6374bc4e2b4db --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/parse.js @@ -0,0 +1,42 @@ +'use strict' + +let Container = require('./container') +let Input = require('./input') +let Parser = require('./parser') + +function parse(css, opts) { + let input = new Input(css, opts) + let parser = new Parser(input) + try { + parser.parse() + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + if (e.name === 'CssSyntaxError' && opts && opts.from) { + if (/\.scss$/i.test(opts.from)) { + e.message += + '\nYou tried to parse SCSS with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-scss parser' + } else if (/\.sass/i.test(opts.from)) { + e.message += + '\nYou tried to parse Sass with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-sass parser' + } else if (/\.less$/i.test(opts.from)) { + e.message += + '\nYou tried to parse Less with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-less parser' + } + } + } + throw e + } + + return parser.root +} + +module.exports = parse +parse.default = parse + +Container.registerParse(parse) diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/parser.js b/e-commerce/node_modules/next/node_modules/postcss/lib/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..2a16584c7fdf2a9b2f685b220f914b0cf4281e20 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/parser.js @@ -0,0 +1,618 @@ +'use strict' + +let AtRule = require('./at-rule') +let Comment = require('./comment') +let Declaration = require('./declaration') +let Root = require('./root') +let Rule = require('./rule') +let tokenizer = require('./tokenize') + +const SAFE_COMMENT_NEIGHBOR = { + empty: true, + space: true +} + +function findLastWithPosition(tokens) { + for (let i = tokens.length - 1; i >= 0; i--) { + let token = tokens[i] + let pos = token[3] || token[2] + if (pos) return pos + } +} + +function tokensToString(tokens, from, to) { + let result = '' + for (let i = from; i < to; i++) result += tokens[i][1] + return result +} + +class Parser { + constructor(input) { + this.input = input + + this.root = new Root() + this.current = this.root + this.spaces = '' + this.semicolon = false + + this.createTokenizer() + this.root.source = { input, start: { column: 1, line: 1, offset: 0 } } + } + + atrule(token) { + let node = new AtRule() + node.name = token[1].slice(1) + if (node.name === '') { + this.unnamedAtrule(node, token) + } + this.init(node, token[2]) + + let type + let prev + let shift + let last = false + let open = false + let params = [] + let brackets = [] + + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + type = token[0] + + if (type === '(' || type === '[') { + brackets.push(type === '(' ? ')' : ']') + } else if (type === '{' && brackets.length > 0) { + brackets.push('}') + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + } + + if (brackets.length === 0) { + if (type === ';') { + node.source.end = this.getPosition(token[2]) + node.source.end.offset++ + this.semicolon = true + break + } else if (type === '{') { + open = true + break + } else if (type === '}') { + if (params.length > 0) { + shift = params.length - 1 + prev = params[shift] + while (prev && prev[0] === 'space') { + prev = params[--shift] + } + if (prev) { + node.source.end = this.getPosition(prev[3] || prev[2]) + node.source.end.offset++ + } + } + this.end(token) + break + } else { + params.push(token) + } + } else { + params.push(token) + } + + if (this.tokenizer.endOfFile()) { + last = true + break + } + } + + node.raws.between = this.spacesAndCommentsFromEnd(params) + if (params.length) { + node.raws.afterName = this.spacesAndCommentsFromStart(params) + this.raw(node, 'params', params) + if (last) { + token = params[params.length - 1] + node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ + this.spaces = node.raws.between + node.raws.between = '' + } + } else { + node.raws.afterName = '' + node.params = '' + } + + if (open) { + node.nodes = [] + this.current = node + } + } + + checkMissedSemicolon(tokens) { + let colon = this.colon(tokens) + if (colon === false) return + + let founded = 0 + let token + for (let j = colon - 1; j >= 0; j--) { + token = tokens[j] + if (token[0] !== 'space') { + founded += 1 + if (founded === 2) break + } + } + // If the token is a word, e.g. `!important`, `red` or any other valid + // property's value. Then we need to return the colon after that word + // token. [3] is the "end" colon of that word. And because we need it + // after that one we do +1 to get the next one. + throw this.input.error( + 'Missed semicolon', + token[0] === 'word' ? token[3] + 1 : token[2] + ) + } + + colon(tokens) { + let brackets = 0 + let prev, token, type + for (let [i, element] of tokens.entries()) { + token = element + type = token[0] + + if (type === '(') { + brackets += 1 + } + if (type === ')') { + brackets -= 1 + } + if (brackets === 0 && type === ':') { + if (!prev) { + this.doubleColon(token) + } else if (prev[0] === 'word' && prev[1] === 'progid') { + continue + } else { + return i + } + } + + prev = token + } + return false + } + + comment(token) { + let node = new Comment() + this.init(node, token[2]) + node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ + + let text = token[1].slice(2, -2) + if (!text.trim()) { + node.text = '' + node.raws.left = text + node.raws.right = '' + } else { + let match = text.match(/^(\s*)([^]*\S)(\s*)$/) + node.text = match[2] + node.raws.left = match[1] + node.raws.right = match[3] + } + } + + createTokenizer() { + this.tokenizer = tokenizer(this.input) + } + + decl(tokens, customProperty) { + let node = new Declaration() + this.init(node, tokens[0][2]) + + let last = tokens[tokens.length - 1] + if (last[0] === ';') { + this.semicolon = true + tokens.pop() + } + + node.source.end = this.getPosition( + last[3] || last[2] || findLastWithPosition(tokens) + ) + node.source.end.offset++ + + let start = 0 + while (tokens[start][0] !== 'word') { + if (start === tokens.length - 1) this.unknownWord([tokens[start]]) + start++ + } + node.raws.before += tokensToString(tokens, 0, start) + node.source.start = this.getPosition(tokens[start][2]) + + let propStart = start + while (start < tokens.length) { + let type = tokens[start][0] + if (type === ':' || type === 'space' || type === 'comment') { + break + } + start++ + } + node.prop = tokensToString(tokens, propStart, start) + + let betweenStart = start + let token + while (start < tokens.length) { + token = tokens[start] + start++ + if (token[0] === ':') break + if (token[0] === 'word' && /\w/.test(token[1])) { + this.unknownWord([token]) + } + } + node.raws.between = tokensToString(tokens, betweenStart, start) + + if (node.prop[0] === '_' || node.prop[0] === '*') { + node.raws.before += node.prop[0] + node.prop = node.prop.slice(1) + } + + let firstSpacesStart = start + while (start < tokens.length) { + let next = tokens[start][0] + if (next !== 'space' && next !== 'comment') break + start++ + } + let firstSpaces = tokens.slice(firstSpacesStart, start) + + tokens = tokens.slice(start) + + this.precheckMissedSemicolon(tokens) + + for (let i = tokens.length - 1; i >= 0; i--) { + token = tokens[i] + if (token[1].toLowerCase() === '!important') { + node.important = true + let string = this.stringFrom(tokens, i) + string = this.spacesFromEnd(tokens) + string + if (string !== ' !important') node.raws.important = string + break + } else if (token[1].toLowerCase() === 'important') { + let cache = tokens.slice(0) + let str = '' + for (let j = i; j > 0; j--) { + let type = cache[j][0] + if (str.trim().startsWith('!') && type !== 'space') { + break + } + str = cache.pop()[1] + str + } + if (str.trim().startsWith('!')) { + node.important = true + node.raws.important = str + tokens = cache + } + } + + if (token[0] !== 'space' && token[0] !== 'comment') { + break + } + } + + let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment') + + if (hasWord) { + node.raws.between += firstSpaces.map(i => i[1]).join('') + firstSpaces = [] + } + this.raw(node, 'value', firstSpaces.concat(tokens), customProperty) + + if (node.value.includes(':') && !customProperty) { + this.checkMissedSemicolon(tokens) + } + } + + doubleColon(token) { + throw this.input.error( + 'Double colon', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } + + emptyRule(token) { + let node = new Rule() + this.init(node, token[2]) + node.selector = '' + node.raws.between = '' + this.current = node + } + + end(token) { + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.semicolon = false + + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.spaces = '' + + if (this.current.parent) { + this.current.source.end = this.getPosition(token[2]) + this.current.source.end.offset++ + this.current = this.current.parent + } else { + this.unexpectedClose(token) + } + } + + endFile() { + if (this.current.parent) this.unclosedBlock() + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.root.source.end = this.getPosition(this.tokenizer.position()) + } + + freeSemicolon(token) { + this.spaces += token[1] + if (this.current.nodes) { + let prev = this.current.nodes[this.current.nodes.length - 1] + if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { + prev.raws.ownSemicolon = this.spaces + this.spaces = '' + prev.source.end = this.getPosition(token[2]) + prev.source.end.offset += prev.raws.ownSemicolon.length + } + } + } + + // Helpers + + getPosition(offset) { + let pos = this.input.fromOffset(offset) + return { + column: pos.col, + line: pos.line, + offset + } + } + + init(node, offset) { + this.current.push(node) + node.source = { + input: this.input, + start: this.getPosition(offset) + } + node.raws.before = this.spaces + this.spaces = '' + if (node.type !== 'comment') this.semicolon = false + } + + other(start) { + let end = false + let type = null + let colon = false + let bracket = null + let brackets = [] + let customProperty = start[1].startsWith('--') + + let tokens = [] + let token = start + while (token) { + type = token[0] + tokens.push(token) + + if (type === '(' || type === '[') { + if (!bracket) bracket = token + brackets.push(type === '(' ? ')' : ']') + } else if (customProperty && colon && type === '{') { + if (!bracket) bracket = token + brackets.push('}') + } else if (brackets.length === 0) { + if (type === ';') { + if (colon) { + this.decl(tokens, customProperty) + return + } else { + break + } + } else if (type === '{') { + this.rule(tokens) + return + } else if (type === '}') { + this.tokenizer.back(tokens.pop()) + end = true + break + } else if (type === ':') { + colon = true + } + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + if (brackets.length === 0) bracket = null + } + + token = this.tokenizer.nextToken() + } + + if (this.tokenizer.endOfFile()) end = true + if (brackets.length > 0) this.unclosedBracket(bracket) + + if (end && colon) { + if (!customProperty) { + while (tokens.length) { + token = tokens[tokens.length - 1][0] + if (token !== 'space' && token !== 'comment') break + this.tokenizer.back(tokens.pop()) + } + } + this.decl(tokens, customProperty) + } else { + this.unknownWord(tokens) + } + } + + parse() { + let token + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + + switch (token[0]) { + case 'space': + this.spaces += token[1] + break + + case ';': + this.freeSemicolon(token) + break + + case '}': + this.end(token) + break + + case 'comment': + this.comment(token) + break + + case 'at-word': + this.atrule(token) + break + + case '{': + this.emptyRule(token) + break + + default: + this.other(token) + break + } + } + this.endFile() + } + + precheckMissedSemicolon(/* tokens */) { + // Hook for Safe Parser + } + + raw(node, prop, tokens, customProperty) { + let token, type + let length = tokens.length + let value = '' + let clean = true + let next, prev + + for (let i = 0; i < length; i += 1) { + token = tokens[i] + type = token[0] + if (type === 'space' && i === length - 1 && !customProperty) { + clean = false + } else if (type === 'comment') { + prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty' + next = tokens[i + 1] ? tokens[i + 1][0] : 'empty' + if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) { + if (value.slice(-1) === ',') { + clean = false + } else { + value += token[1] + } + } else { + clean = false + } + } else { + value += token[1] + } + } + if (!clean) { + let raw = tokens.reduce((all, i) => all + i[1], '') + node.raws[prop] = { raw, value } + } + node[prop] = value + } + + rule(tokens) { + tokens.pop() + + let node = new Rule() + this.init(node, tokens[0][2]) + + node.raws.between = this.spacesAndCommentsFromEnd(tokens) + this.raw(node, 'selector', tokens) + this.current = node + } + + spacesAndCommentsFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space' && lastTokenType !== 'comment') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + // Errors + + spacesAndCommentsFromStart(tokens) { + let next + let spaces = '' + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + spaces += tokens.shift()[1] + } + return spaces + } + + spacesFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + stringFrom(tokens, from) { + let result = '' + for (let i = from; i < tokens.length; i++) { + result += tokens[i][1] + } + tokens.splice(from, tokens.length - from) + return result + } + + unclosedBlock() { + let pos = this.current.source.start + throw this.input.error('Unclosed block', pos.line, pos.column) + } + + unclosedBracket(bracket) { + throw this.input.error( + 'Unclosed bracket', + { offset: bracket[2] }, + { offset: bracket[2] + 1 } + ) + } + + unexpectedClose(token) { + throw this.input.error( + 'Unexpected }', + { offset: token[2] }, + { offset: token[2] + 1 } + ) + } + + unknownWord(tokens) { + throw this.input.error( + 'Unknown word ' + tokens[0][1], + { offset: tokens[0][2] }, + { offset: tokens[0][2] + tokens[0][1].length } + ) + } + + unnamedAtrule(node, token) { + throw this.input.error( + 'At-rule without name', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } +} + +module.exports = Parser diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/postcss.d.mts b/e-commerce/node_modules/next/node_modules/postcss/lib/postcss.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..eaec8681f1b412534556620f2b0139045e3bfb51 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/postcss.d.mts @@ -0,0 +1,66 @@ +export { + // Type-only exports + AcceptedPlugin, + AnyNode, + atRule, + AtRule, + AtRuleProps, + Builder, + ChildNode, + ChildProps, + comment, + Comment, + CommentProps, + Container, + ContainerProps, + CssSyntaxError, + decl, + Declaration, + DeclarationProps, + // postcss function / namespace + default, + document, + Document, + DocumentProps, + FilePosition, + fromJSON, + Helpers, + Input, + JSONHydrator, + // This is a class, but it’s not re-exported. That’s why it’s exported as type-only here. + type LazyResult, + list, + Message, + Node, + NodeErrorOptions, + NodeProps, + OldPlugin, + parse, + Parser, + // @ts-expect-error This value exists, but it’s untyped. + plugin, + Plugin, + PluginCreator, + Position, + Postcss, + ProcessOptions, + Processor, + Result, + root, + Root, + RootProps, + rule, + Rule, + RuleProps, + Source, + SourceMap, + SourceMapOptions, + Stringifier, + // Value exports from postcss.mjs + stringify, + Syntax, + TransformCallback, + Transformer, + Warning, + WarningOptions +} from './postcss.js' diff --git a/e-commerce/node_modules/next/node_modules/postcss/lib/postcss.d.ts b/e-commerce/node_modules/next/node_modules/postcss/lib/postcss.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41bf40f9b9204aaa387c56ea34f18bc21ac66523 --- /dev/null +++ b/e-commerce/node_modules/next/node_modules/postcss/lib/postcss.d.ts @@ -0,0 +1,464 @@ +import { RawSourceMap, SourceMapGenerator } from 'source-map-js' + +import AtRule, { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container, { ContainerProps, NewChild } from './container.js' +import CssSyntaxError from './css-syntax-error.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Document, { DocumentProps } from './document.js' +import Input, { FilePosition } from './input.js' +import LazyResult from './lazy-result.js' +import list from './list.js' +import Node, { + AnyNode, + ChildNode, + ChildProps, + NodeErrorOptions, + NodeProps, + Position, + Source +} from './node.js' +import Processor from './processor.js' +import Result, { Message } from './result.js' +import Root, { RootProps } from './root.js' +import Rule, { RuleProps } from './rule.js' +import Warning, { WarningOptions } from './warning.js' + +type DocumentProcessor = ( + document: Document, + helper: postcss.Helpers +) => Promise | void +type RootProcessor = ( + root: Root, + helper: postcss.Helpers +) => Promise | void +type DeclarationProcessor = ( + decl: Declaration, + helper: postcss.Helpers +) => Promise | void +type RuleProcessor = ( + rule: Rule, + helper: postcss.Helpers +) => Promise | void +type AtRuleProcessor = ( + atRule: AtRule, + helper: postcss.Helpers +) => Promise | void +type CommentProcessor = ( + comment: Comment, + helper: postcss.Helpers +) => Promise | void + +interface Processors { + /** + * Will be called on all`AtRule` nodes. + * + * Will be called again on node or children changes. + */ + AtRule?: { [name: string]: AtRuleProcessor } | AtRuleProcessor + + /** + * Will be called on all `AtRule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + AtRuleExit?: { [name: string]: AtRuleProcessor } | AtRuleProcessor + + /** + * Will be called on all `Comment` nodes. + * + * Will be called again on node or children changes. + */ + Comment?: CommentProcessor + + /** + * Will be called on all `Comment` nodes after listeners + * for `Comment` event. + * + * Will be called again on node or children changes. + */ + CommentExit?: CommentProcessor + + /** + * Will be called on all `Declaration` nodes after listeners + * for `Declaration` event. + * + * Will be called again on node or children changes. + */ + Declaration?: { [prop: string]: DeclarationProcessor } | DeclarationProcessor + + /** + * Will be called on all `Declaration` nodes. + * + * Will be called again on node or children changes. + */ + DeclarationExit?: + | { [prop: string]: DeclarationProcessor } + | DeclarationProcessor + + /** + * Will be called on `Document` node. + * + * Will be called again on children changes. + */ + Document?: DocumentProcessor + + /** + * Will be called on `Document` node, when all children will be processed. + * + * Will be called again on children changes. + */ + DocumentExit?: DocumentProcessor + + /** + * Will be called on `Root` node once. + */ + Once?: RootProcessor + + /** + * Will be called on `Root` node once, when all children will be processed. + */ + OnceExit?: RootProcessor + + /** + * Will be called on `Root` node. + * + * Will be called again on children changes. + */ + Root?: RootProcessor + + /** + * Will be called on `Root` node, when all children will be processed. + * + * Will be called again on children changes. + */ + RootExit?: RootProcessor + + /** + * Will be called on all `Rule` nodes. + * + * Will be called again on node or children changes. + */ + Rule?: RuleProcessor + + /** + * Will be called on all `Rule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + RuleExit?: RuleProcessor +} + +declare namespace postcss { + export { + AnyNode, + AtRule, + AtRuleProps, + ChildNode, + ChildProps, + Comment, + CommentProps, + Container, + ContainerProps, + CssSyntaxError, + Declaration, + DeclarationProps, + Document, + DocumentProps, + FilePosition, + Input, + LazyResult, + list, + Message, + NewChild, + Node, + NodeErrorOptions, + NodeProps, + Position, + Processor, + Result, + Root, + RootProps, + Rule, + RuleProps, + Source, + Warning, + WarningOptions + } + + export type SourceMap = { + toJSON(): RawSourceMap + } & SourceMapGenerator + + export type Helpers = { postcss: Postcss; result: Result } & Postcss + + export interface Plugin extends Processors { + postcssPlugin: string + prepare?: (result: Result) => Processors + } + + export interface PluginCreator { + (opts?: PluginOptions): Plugin | Processor + postcss: true + } + + export interface Transformer extends TransformCallback { + postcssPlugin: string + postcssVersion: string + } + + export interface TransformCallback { + (root: Root, result: Result): Promise | void + } + + export interface OldPlugin extends Transformer { + (opts?: T): Transformer + postcss: Transformer + } + + export type AcceptedPlugin = + | { + postcss: Processor | TransformCallback + } + | OldPlugin + | Plugin + | PluginCreator + | Processor + | TransformCallback + + export interface Parser { + ( + css: { toString(): string } | string, + opts?: Pick + ): RootNode + } + + export interface Builder { + (part: string, node?: AnyNode, type?: 'end' | 'start'): void + } + + export interface Stringifier { + (node: AnyNode, builder: Builder): void + } + + export interface JSONHydrator { + (data: object): Node + (data: object[]): Node[] + } + + export interface Syntax { + /** + * Function to generate AST by string. + */ + parse?: Parser + + /** + * Class to generate string by AST. + */ + stringify?: Stringifier + } + + export interface SourceMapOptions { + /** + * Use absolute path in generated source map. + */ + absolute?: boolean + + /** + * Indicates that PostCSS should add annotation comments to the CSS. + * By default, PostCSS will always add a comment with a path + * to the source map. PostCSS will not add annotations to CSS files + * that do not contain any comments. + * + * By default, PostCSS presumes that you want to save the source map as + * `opts.to + '.map'` and will use this path in the annotation comment. + * A different path can be set by providing a string value for annotation. + * + * If you have set `inline: true`, annotation cannot be disabled. + */ + annotation?: ((file: string, root: Root) => string) | boolean | string + + /** + * Override `from` in map’s sources. + */ + from?: string + + /** + * Indicates that the source map should be embedded in the output CSS + * as a Base64-encoded comment. By default, it is `true`. + * But if all previous maps are external, not inline, PostCSS will not embed + * the map even if you do not set this option. + * + * If you have an inline source map, the result.map property will be empty, + * as the source map will be contained within the text of `result.css`. + */ + inline?: boolean + + /** + * Source map content from a previous processing step (e.g., Sass). + * + * PostCSS will try to read the previous source map + * automatically (based on comments within the source CSS), but you can use + * this option to identify it manually. + * + * If desired, you can omit the previous map with prev: `false`. + */ + prev?: ((file: string) => string) | boolean | object | string + + /** + * Indicates that PostCSS should set the origin content (e.g., Sass source) + * of the source map. By default, it is true. But if all previous maps do not + * contain sources content, PostCSS will also leave it out even if you + * do not set this option. + */ + sourcesContent?: boolean + } + + export interface ProcessOptions { + /** + * Input file if it is not simple CSS file, but HTML with ", + `` + ].join("") + result2.join(""); + return { value: { html: html2, scriptNonce: scriptNonce2 }, size: html2.length }; + }); + return { html, scriptNonce, pageId: snapshot3.pageId, frameId: snapshot3.frameId, index: this._index }; + } + resourceByUrl(url3, method2) { + const snapshot3 = this._snapshot; + let sameFrameResource; + let otherFrameResource; + for (const resource of this._resources) { + if (typeof resource._monotonicTime === "number" && resource._monotonicTime >= snapshot3.timestamp) + break; + if (resource.response.status === 304) { + continue; + } + if (resource.request.url === url3 && resource.request.method === method2) { + if (resource._frameref === snapshot3.frameId) + sameFrameResource = resource; + else + otherFrameResource = resource; + } + } + let result2 = sameFrameResource ?? otherFrameResource; + if (result2 && method2.toUpperCase() === "GET") { + let override = snapshot3.resourceOverrides.find((o) => o.url === url3); + if (override?.ref) { + const index = this._index - override.ref; + if (index >= 0 && index < this._snapshots.length) + override = this._snapshots[index].resourceOverrides.find((o) => o.url === url3); + } + if (override?.file) { + result2 = { + ...result2, + response: { + ...result2.response, + content: { + ...result2.response.content, + _file: override.file + } + } + }; + } + } + return result2; + } + }; + autoClosing = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]); + kAllowedMetaHttpEquivs = /* @__PURE__ */ new Set(["content-type", "content-language", "default-style", "x-ua-compatible"]); + schemas = ["about:", "blob:", "data:", "file:", "ftp:", "http:", "https:", "mailto:", "sftp:", "ws:", "wss:"]; + kLegacyBlobPrefix = "http://playwright.bloburl/#"; + urlInCSSRegex = /url\(['"]?([\w-]+:)\/\//ig; + blankSnapshotUrl = "data:text/html;base64," + btoa(``); + } +}); + +// packages/isomorphic/lruCache.ts +var LRUCache; +var init_lruCache = __esm({ + "packages/isomorphic/lruCache.ts"() { + "use strict"; + LRUCache = class { + constructor(maxSize) { + this._maxSize = maxSize; + this._map = /* @__PURE__ */ new Map(); + this._size = 0; + } + getOrCompute(key, compute) { + if (this._map.has(key)) { + const result3 = this._map.get(key); + this._map.delete(key); + this._map.set(key, result3); + return result3.value; + } + const result2 = compute(); + while (this._map.size && this._size + result2.size > this._maxSize) { + const [firstKey, firstValue] = this._map.entries().next().value; + this._size -= firstValue.size; + this._map.delete(firstKey); + } + this._map.set(key, result2); + this._size += result2.size; + return result2.value; + } + }; + } +}); + +// packages/isomorphic/trace/snapshotStorage.ts +function callIdAndPhase(callId, phase) { + return `${callId}/${phase}`; +} +var SnapshotStorage; +var init_snapshotStorage = __esm({ + "packages/isomorphic/trace/snapshotStorage.ts"() { + "use strict"; + init_snapshotRenderer(); + init_lruCache(); + SnapshotStorage = class { + constructor() { + this._snapshotsByFrameId = /* @__PURE__ */ new Map(); + this._renderersByCallIdAndPhase = /* @__PURE__ */ new Map(); + this._cache = new LRUCache(1e8); + // 100MB per each trace + this._resources = []; + this._resourceUrlsWithOverrides = /* @__PURE__ */ new Set(); + } + addResource(resource) { + resource.request.url = rewriteURLForCustomProtocol(resource.request.url); + this._resources.push(resource); + } + addFrameSnapshot(snapshot3, screencastFrames) { + for (const override of snapshot3.resourceOverrides) + override.url = rewriteURLForCustomProtocol(override.url); + let frameSnapshots = this._snapshotsByFrameId.get(snapshot3.frameId); + if (!frameSnapshots) { + frameSnapshots = []; + this._snapshotsByFrameId.set(snapshot3.frameId, frameSnapshots); + } + frameSnapshots.push(snapshot3); + const renderer = new SnapshotRenderer(this._cache, this._resources, frameSnapshots, screencastFrames, frameSnapshots.length - 1); + if (snapshot3.phase) { + const key = callIdAndPhase(snapshot3.callId, snapshot3.phase); + let renderers = this._renderersByCallIdAndPhase.get(key); + if (!renderers) { + renderers = []; + this._renderersByCallIdAndPhase.set(key, renderers); + } + renderers.push(renderer); + } + return renderer; + } + snapshotForCall(callId, phase, frameId) { + const renderers = this._renderersByCallIdAndPhase.get(callIdAndPhase(callId, phase)) || []; + return renderers.find((r) => frameId ? r.snapshot().frameId === frameId : r.snapshot().isMainFrame); + } + snapshotsForTest() { + return [...this._renderersByCallIdAndPhase.keys()]; + } + finalize() { + this._resources.sort((a, b) => (a._monotonicTime || 0) - (b._monotonicTime || 0)); + for (const frameSnapshots of this._snapshotsByFrameId.values()) { + for (const snapshot3 of frameSnapshots) { + for (const override of snapshot3.resourceOverrides) + this._resourceUrlsWithOverrides.add(override.url); + } + } + } + hasResourceOverride(url3) { + return this._resourceUrlsWithOverrides.has(url3); + } + }; + } +}); + +// packages/isomorphic/trace/traceUtils.ts +function createCallIdGenerator() { + const alphabet = "abcdefghijklmnopqrstuvwxyz"; + let prefix = ""; + for (let i = 0; i < 4; i++) + prefix += alphabet[Math.floor(Math.random() * alphabet.length)]; + return () => `${prefix}@${++lastIdOrdinal}`; +} +function legacyCallId(ordinal) { + return `call@${ordinal}`; +} +function parseClientSideCallMetadata(data) { + const result2 = /* @__PURE__ */ new Map(); + const { files, stacks } = data; + for (const s of stacks) { + const [id, ff] = s; + result2.set(id, ff.map((f) => ({ file: files[f[0]], line: f[1], column: f[2], function: f[3] }))); + } + return result2; +} +function serializeClientSideCallMetadata(metadatas) { + const fileNames = /* @__PURE__ */ new Map(); + const stacks = []; + for (const m of metadatas) { + if (!m.stack || !m.stack.length) + continue; + const stack = []; + for (const frame of m.stack) { + let ordinal = fileNames.get(frame.file); + if (typeof ordinal !== "number") { + ordinal = fileNames.size; + fileNames.set(frame.file, ordinal); + } + const stackFrame = [ordinal, frame.line || 0, frame.column || 0, frame.function || ""]; + stack.push(stackFrame); + } + stacks.push([m.id, stack]); + } + return { files: [...fileNames.keys()], stacks }; +} +var lastIdOrdinal; +var init_traceUtils = __esm({ + "packages/isomorphic/trace/traceUtils.ts"() { + "use strict"; + lastIdOrdinal = 0; + } +}); + +// packages/isomorphic/trace/traceModernizer.ts +var TraceVersionError, latestVersion, lastApiRequestRefOrdinal, TraceModernizer; +var init_traceModernizer = __esm({ + "packages/isomorphic/trace/traceModernizer.ts"() { + "use strict"; + init_traceUtils(); + TraceVersionError = class extends Error { + constructor(message) { + super(message); + this.name = "TraceVersionError"; + } + }; + latestVersion = 10; + lastApiRequestRefOrdinal = 0; + TraceModernizer = class { + constructor(contextEntry, snapshotStorage) { + this._actionMap = /* @__PURE__ */ new Map(); + this._pageEntries = /* @__PURE__ */ new Map(); + this._jsHandles = /* @__PURE__ */ new Map(); + this._consoleObjects = /* @__PURE__ */ new Map(); + this._snapshotPhases = /* @__PURE__ */ new Map(); + this._legacyCallIdToStepId = /* @__PURE__ */ new Map(); + this._contextEntry = contextEntry; + this._snapshotStorage = snapshotStorage; + } + appendTrace(trace) { + for (const line of trace.split("\n")) + this._appendEvent(line); + } + appendStacks(stacks) { + const data = JSON.parse(stacks); + const normalized = data.stacks.map(([id, ...rest]) => { + const callId = typeof id === "number" ? legacyCallId(id) : id; + return [this._legacyCallIdToStepId.get(callId) ?? callId, ...rest]; + }); + const callMetadata = parseClientSideCallMetadata({ files: data.files, stacks: normalized }); + for (const action of this._actionMap.values()) + action.stack = action.stack || callMetadata.get(action.callId); + } + actions() { + return [...this._actionMap.values()]; + } + _collectSnapshotPhase(snapshotName, phase) { + if (snapshotName) + this._snapshotPhases.set(snapshotName, phase); + } + _pageEntry(pageId4) { + let pageEntry = this._pageEntries.get(pageId4); + if (!pageEntry) { + pageEntry = { + pageId: pageId4, + screencastFrames: [] + }; + this._pageEntries.set(pageId4, pageEntry); + this._contextEntry.pages.push(pageEntry); + } + return pageEntry; + } + _appendEvent(line) { + if (!line) + return; + const events = this._modernize(JSON.parse(line)); + for (const event of events) + this._innerAppendEvent(event); + } + _innerAppendEvent(event) { + const contextEntry = this._contextEntry; + switch (event.type) { + case "context-options": { + if (event.version > latestVersion) + throw new TraceVersionError("The trace was created by a newer version of Playwright and is not supported by this version of the viewer. Please use latest Playwright to open the trace."); + this._version = event.version; + contextEntry.origin = event.origin; + contextEntry.browserName = event.browserName; + contextEntry.channel = event.channel; + contextEntry.title = event.title; + contextEntry.platform = event.platform; + contextEntry.playwrightVersion = event.playwrightVersion; + contextEntry.wallTime = event.wallTime; + contextEntry.monotonicTime = event.monotonicTime; + contextEntry.startTime = event.monotonicTime; + contextEntry.sdkLanguage = event.sdkLanguage; + contextEntry.options = event.options; + contextEntry.testIdAttributeName = event.testIdAttributeName; + contextEntry.testTimeout = event.testTimeout; + contextEntry.annotations = event.annotations; + break; + } + case "screencast-frame": { + this._pageEntry(event.pageId).screencastFrames.push(event); + break; + } + case "screenshot": { + contextEntry.screenshots.push(event); + break; + } + case "video": { + contextEntry.videos.push(event); + break; + } + case "aria-snapshot": { + contextEntry.ariaSnapshots.push(event); + break; + } + case "before": { + this._actionMap.set(event.callId, { ...event, type: "action", endTime: 0, log: [] }); + break; + } + case "input": { + const existing = this._actionMap.get(event.callId); + existing.point = event.point; + existing.box = event.box; + break; + } + case "log": { + const existing = this._actionMap.get(event.callId); + if (!existing) + return; + existing.log.push({ + time: event.time, + message: event.message + }); + break; + } + case "after": { + const existing = this._actionMap.get(event.callId); + existing.endTime = event.endTime; + existing.result = event.result; + existing.error = event.error; + existing.attachments = event.attachments; + existing.annotations = event.annotations; + if (event.point) + existing.point = event.point; + break; + } + case "action": { + this._actionMap.set(event.callId, { ...event, log: [] }); + break; + } + case "event": { + if ((event.method === "page" || event.method === "pageClosed") && event.params?.pageId) + this._pageEntry(event.params.pageId); + contextEntry.events.push(event); + break; + } + case "stdout": { + contextEntry.stdio.push(event); + break; + } + case "stderr": { + contextEntry.stdio.push(event); + break; + } + case "error": { + contextEntry.errors.push(event); + break; + } + case "console": { + contextEntry.events.push(event); + break; + } + case "resource-snapshot": + this._snapshotStorage.addResource(event.snapshot); + contextEntry.resources.push(event.snapshot); + break; + case "frame-snapshot": { + const snapshot3 = event.snapshot; + this._snapshotStorage.addFrameSnapshot(snapshot3, this._pageEntry(snapshot3.pageId).screencastFrames); + if (snapshot3.isMainFrame && snapshot3.phase) + contextEntry.domSnapshots.push({ callId: snapshot3.callId, phase: snapshot3.phase }); + break; + } + } + if ("pageId" in event && event.pageId) + this._pageEntry(event.pageId); + if (event.type === "action" || event.type === "before") + contextEntry.startTime = Math.min(contextEntry.startTime, event.startTime); + if (event.type === "action" || event.type === "after") + contextEntry.endTime = Math.max(contextEntry.endTime, event.endTime); + if (event.type === "event") { + contextEntry.startTime = Math.min(contextEntry.startTime, event.time); + contextEntry.endTime = Math.max(contextEntry.endTime, event.time); + } + if (event.type === "screencast-frame") { + contextEntry.startTime = Math.min(contextEntry.startTime, event.timestamp); + contextEntry.endTime = Math.max(contextEntry.endTime, event.timestamp); + } + } + _processedContextCreatedEvent() { + return this._version !== void 0; + } + _modernize(event) { + let version3 = this._version ?? event.version ?? 6; + let events = [event]; + for (; version3 < latestVersion; ++version3) + events = this[`_modernize_${version3}_to_${version3 + 1}`].call(this, events); + return events; + } + _modernize_0_to_1(events) { + for (const event of events) { + if (event.type !== "action") + continue; + if (typeof event.metadata.error === "string") + event.metadata.error = { error: { name: "Error", message: event.metadata.error } }; + } + return events; + } + _modernize_1_to_2(events) { + for (const event of events) { + if (event.type !== "frame-snapshot" || !event.snapshot.isMainFrame) + continue; + event.snapshot.viewport = this._contextEntry.options?.viewport || { width: 1280, height: 720 }; + } + return events; + } + _modernize_2_to_3(events) { + for (const event of events) { + if (event.type !== "resource-snapshot" || event.snapshot.request) + continue; + const resource = event.snapshot; + event.snapshot = { + _frameref: resource.frameId, + request: { + url: resource.url, + method: resource.method, + headers: resource.requestHeaders, + postData: resource.requestSha1 ? { _sha1: resource.requestSha1 } : void 0 + }, + response: { + status: resource.status, + headers: resource.responseHeaders, + content: { + mimeType: resource.contentType, + _sha1: resource.responseSha1 + } + }, + _monotonicTime: resource.timestamp + }; + } + return events; + } + _modernize_3_to_4(events) { + const result2 = []; + for (const event of events) { + const e = this._modernize_event_3_to_4(event); + if (e) + result2.push(e); + } + return result2; + } + _modernize_event_3_to_4(event) { + if (event.type !== "action" && event.type !== "event") { + return event; + } + const metadata = event.metadata; + if (metadata.internal || metadata.method.startsWith("tracing")) + return null; + if (event.type === "event") { + if (metadata.method === "__create__" && metadata.type === "ConsoleMessage") { + return { + type: "object", + class: metadata.type, + guid: metadata.params.guid, + initializer: metadata.params.initializer + }; + } + return { + type: "event", + time: metadata.startTime, + class: metadata.type, + method: metadata.method, + params: metadata.params, + pageId: metadata.pageId + }; + } + return { + type: "action", + callId: metadata.id, + startTime: metadata.startTime, + endTime: metadata.endTime, + apiName: metadata.apiName || metadata.type + "." + metadata.method, + class: metadata.type, + method: metadata.method, + params: metadata.params, + // eslint-disable-next-line no-restricted-globals + wallTime: metadata.wallTime || Date.now(), + log: metadata.log, + beforeSnapshot: metadata.snapshots.find((s) => s.title === "before")?.snapshotName, + inputSnapshot: metadata.snapshots.find((s) => s.title === "input")?.snapshotName, + afterSnapshot: metadata.snapshots.find((s) => s.title === "after")?.snapshotName, + error: metadata.error?.error, + result: metadata.result, + point: metadata.point, + pageId: metadata.pageId + }; + } + _modernize_4_to_5(events) { + const result2 = []; + for (const event of events) { + const e = this._modernize_event_4_to_5(event); + if (e) + result2.push(e); + } + return result2; + } + _modernize_event_4_to_5(event) { + if (event.type === "event" && event.method === "__create__" && event.class === "JSHandle") + this._jsHandles.set(event.params.guid, event.params.initializer); + if (event.type === "object") { + if (event.class !== "ConsoleMessage") + return null; + const args = event.initializer.args?.map((arg2) => { + if (arg2.guid) { + const handle = this._jsHandles.get(arg2.guid); + return { preview: handle?.preview || "", value: "" }; + } + return { preview: arg2.preview || "", value: arg2.value || "" }; + }); + this._consoleObjects.set(event.guid, { + type: event.initializer.type, + text: event.initializer.text, + location: event.initializer.location, + args + }); + return null; + } + if (event.type === "event" && event.method === "console") { + const consoleMessage = this._consoleObjects.get(event.params.message?.guid || ""); + if (!consoleMessage) + return null; + return { + type: "console", + time: event.time, + pageId: event.pageId, + messageType: consoleMessage.type, + text: consoleMessage.text, + args: consoleMessage.args, + location: consoleMessage.location + }; + } + return event; + } + _modernize_5_to_6(events) { + const result2 = []; + for (const event of events) { + result2.push(event); + if (event.type !== "after" || !event.log.length) + continue; + for (const log2 of event.log) { + result2.push({ + type: "log", + callId: event.callId, + message: log2, + time: -1 + }); + } + } + return result2; + } + _modernize_6_to_7(events) { + const result2 = []; + if (!this._processedContextCreatedEvent() && events[0].type !== "context-options") { + const event = { + type: "context-options", + origin: "testRunner", + version: 6, + browserName: "", + options: {}, + platform: "unknown", + wallTime: 0, + monotonicTime: 0, + sdkLanguage: "javascript", + contextId: "" + }; + result2.push(event); + } + for (const event of events) { + if (event.type === "context-options") { + result2.push({ ...event, monotonicTime: 0, origin: "library", contextId: "" }); + continue; + } + if (event.type === "before" || event.type === "action") { + if (!this._contextEntry.monotonicTime) { + this._contextEntry.monotonicTime = event.startTime; + this._contextEntry.wallTime = event.wallTime; + } + const eventAsV6 = event; + const eventAsV7 = event; + eventAsV7.stepId = `${eventAsV6.apiName}@${eventAsV6.wallTime}`; + result2.push(eventAsV7); + } else { + result2.push(event); + } + } + return result2; + } + _modernize_7_to_8(events) { + const result2 = []; + for (const event of events) { + if (event.type === "before" || event.type === "action") { + const eventAsV7 = event; + const eventAsV8 = event; + if (eventAsV7.apiName) { + eventAsV8.title = eventAsV7.apiName; + delete eventAsV8.apiName; + } + eventAsV8.stepId = eventAsV7.stepId ?? eventAsV7.callId; + result2.push(eventAsV8); + } else { + result2.push(event); + } + } + return result2; + } + _modernize_8_to_9(events) { + for (const event of events) { + if (event.type === "before" || event.type === "input" || event.type === "after" || event.type === "action") { + const action = event; + this._collectSnapshotPhase(action.beforeSnapshot, "before"); + this._collectSnapshotPhase(action.inputSnapshot, "action"); + this._collectSnapshotPhase(action.afterSnapshot, "after"); + delete action.beforeSnapshot; + delete action.inputSnapshot; + delete action.afterSnapshot; + } + if (event.type === "after" || event.type === "action") { + for (const attachment of event.attachments || []) { + if (attachment.sha1) { + attachment.file = "resources/" + attachment.sha1; + delete attachment.sha1; + } + } + } + if (event.type === "screencast-frame" && event.sha1) { + event.file = "resources/" + event.sha1; + delete event.sha1; + } + if (event.type === "frame-snapshot") { + if (event.snapshot.snapshotName) + event.snapshot.phase = this._snapshotPhases.get(event.snapshot.snapshotName); + for (const override of event.snapshot.resourceOverrides || []) { + if (override.sha1) { + override.file = "resources/" + override.sha1; + delete override.sha1; + } + } + } + if (event.type === "resource-snapshot") { + const postData = event.snapshot.request?.postData; + if (postData?._sha1) { + postData._file = "resources/" + postData._sha1; + delete postData._sha1; + } + const content = event.snapshot.response?.content; + if (content?._sha1) { + content._file = "resources/" + content._sha1; + delete content._sha1; + } + if (event.snapshot._apiRequest) { + if (!this._apiRequestRef) + this._apiRequestRef = "api-request-context@" + ++lastApiRequestRefOrdinal; + event.snapshot._apiRequestRef = this._apiRequestRef; + delete event.snapshot._apiRequest; + } + } + } + return events; + } + _modernize_9_to_10(events) { + for (const event of events) { + if (event.type === "before" || event.type === "action") { + if (event.stepId && event.stepId !== event.callId) + this._legacyCallIdToStepId.set(event.callId, event.stepId); + delete event.stepId; + if (event.parentId) + event.parentId = this._legacyCallIdToStepId.get(event.parentId) ?? event.parentId; + } + if (event.type === "before" || event.type === "input" || event.type === "after" || event.type === "action" || event.type === "log") + event.callId = this._legacyCallIdToStepId.get(event.callId) ?? event.callId; + if (event.type === "frame-snapshot") + event.snapshot.callId = this._legacyCallIdToStepId.get(event.snapshot.callId) ?? event.snapshot.callId; + } + return events; + } + }; + } +}); + +// packages/isomorphic/trace/traceLoader.ts +function stripEncodingFromContentType(contentType) { + const charset = contentType.match(/^(.*);\s*charset=.*$/); + if (charset) + return charset[1]; + return contentType; +} +function createEmptyContext() { + return { + origin: "testRunner", + startTime: Number.MAX_SAFE_INTEGER, + wallTime: Number.MAX_SAFE_INTEGER, + monotonicTime: 0, + endTime: 0, + browserName: "", + options: { + deviceScaleFactor: 1, + isMobile: false, + viewport: { width: 1280, height: 800 } + }, + pages: [], + resources: [], + actions: [], + screenshots: [], + ariaSnapshots: [], + domSnapshots: [], + videos: [], + events: [], + errors: [], + stdio: [], + hasSource: false + }; +} +var TraceLoader; +var init_traceLoader = __esm({ + "packages/isomorphic/trace/traceLoader.ts"() { + "use strict"; + init_snapshotStorage(); + init_traceModernizer(); + TraceLoader = class { + constructor() { + this.contextEntries = []; + this._resourceToContentType = /* @__PURE__ */ new Map(); + } + async load(backend, traceFile, unzipProgress) { + this._backend = backend; + const prefix = traceFile?.match(/(.+)\.trace$/)?.[1]; + const prefixes = []; + let hasSource = false; + for (const entryName of await this._backend.entryNames()) { + const match = entryName.match(/(.+)\.trace$/); + if (match && (!prefix || prefix === match[1])) + prefixes.push(match[1] || ""); + if (entryName.startsWith("src/") || entryName.includes("src@")) + hasSource = true; + } + if (!prefixes.length) + throw new Error("Cannot find .trace file"); + this._snapshotStorage = new SnapshotStorage(); + const total = prefixes.length * 3; + let done = 0; + for (const prefix2 of prefixes) { + const contextEntry = createEmptyContext(); + contextEntry.hasSource = hasSource; + const modernizer = new TraceModernizer(contextEntry, this._snapshotStorage); + const trace = await this._backend.readText(prefix2 + ".trace") || ""; + modernizer.appendTrace(trace); + unzipProgress?.(++done, total); + const network = await this._backend.readText(prefix2 + ".network") || ""; + modernizer.appendTrace(network); + unzipProgress?.(++done, total); + const stacks = await this._backend.readText(prefix2 + ".stacks"); + if (stacks) + modernizer.appendStacks(stacks); + unzipProgress?.(++done, total); + contextEntry.actions = modernizer.actions().sort((a1, a2) => a1.startTime - a2.startTime); + if (!backend.isLive()) { + for (const action of contextEntry.actions.slice().reverse()) { + if (!action.endTime && !action.error) { + for (const a of contextEntry.actions) { + if (a.parentId === action.callId && action.endTime < a.endTime) + action.endTime = a.endTime; + } + } + } + } + for (const resource of contextEntry.resources) { + if (resource.request.postData?._file) + this._resourceToContentType.set(resource.request.postData._file, stripEncodingFromContentType(resource.request.postData.mimeType)); + if (resource.response.content?._file) + this._resourceToContentType.set(resource.response.content._file, stripEncodingFromContentType(resource.response.content.mimeType)); + } + this.contextEntries.push(contextEntry); + } + this._snapshotStorage.finalize(); + } + async hasEntry(filename) { + return this._backend.hasEntry(filename); + } + async resourceEntry(file) { + const blob = await this._backend.readBlob(file); + const contentType = this._resourceToContentType.get(file); + if (!blob || contentType === void 0 || contentType === "x-unknown") + return blob; + return new Blob([blob], { type: contentType }); + } + storage() { + return this._snapshotStorage; + } + }; + } +}); + +// packages/isomorphic/trace/traceModel.ts +function resourceOwnerRef(resource) { + return resource.pageref ?? resource._serviceWorkerRef ?? resource._apiRequestRef; +} +function mergeActionsAndUpdateTiming(contexts) { + const result2 = mergeActionsAndUpdateTimingSameTrace(contexts); + result2.sort((a1, a2) => { + if (a2.parentId === a1.callId) + return 1; + if (a1.parentId === a2.callId) + return -1; + return a1.endTime - a2.endTime; + }); + for (let i = 1; i < result2.length; ++i) + result2[i][prevByEndTimeSymbol] = result2[i - 1]; + result2.sort((a1, a2) => { + if (a2.parentId === a1.callId) + return -1; + if (a1.parentId === a2.callId) + return 1; + return a1.startTime - a2.startTime; + }); + for (let i = 0; i + 1 < result2.length; ++i) + result2[i][nextByStartTimeSymbol] = result2[i + 1]; + return result2; +} +function mergeActionsAndUpdateTimingSameTrace(contexts) { + const map = /* @__PURE__ */ new Map(); + const libraryContexts = contexts.filter((context) => context.origin === "library"); + const testRunnerContexts = contexts.filter((context) => context.origin === "testRunner"); + if (!testRunnerContexts.length || !libraryContexts.length) { + return contexts.map((context) => { + return context.actions.map((action) => ({ ...action })); + }).flat(); + } + const timeOrigin2 = (context) => context.wallTime - context.monotonicTime; + const runnerContext = testRunnerContexts.find((context) => context.monotonicTime); + for (const context of libraryContexts) { + if (runnerContext && context.monotonicTime) + adjustMonotonicTime(context, timeOrigin2(context) - timeOrigin2(runnerContext)); + } + for (const context of libraryContexts) { + for (const action of context.actions) + map.set(action.callId, { ...action }); + } + for (const context of testRunnerContexts) { + for (const action of context.actions) { + const existing = map.get(action.callId); + if (!existing) { + map.set(action.callId, { ...action }); + continue; + } + if (action.error) + existing.error = action.error; + if (action.attachments) + existing.attachments = action.attachments; + if (action.annotations) + existing.annotations = action.annotations; + if (action.parentId) + existing.parentId = action.parentId; + if (action.group) + existing.group = action.group; + existing.startTime = action.startTime; + existing.endTime = action.endTime; + } + } + return [...map.values()]; +} +function adjustMonotonicTime(context, monotonicTimeDelta) { + if (!monotonicTimeDelta) + return; + context.startTime += monotonicTimeDelta; + context.endTime += monotonicTimeDelta; + context.monotonicTime += monotonicTimeDelta; + for (const action of context.actions) { + if (action.startTime) + action.startTime += monotonicTimeDelta; + if (action.endTime) + action.endTime += monotonicTimeDelta; + } + for (const event of context.events) + event.time += monotonicTimeDelta; + for (const event of context.stdio) + event.timestamp += monotonicTimeDelta; + for (const page of context.pages) { + for (const frame of page.screencastFrames) + frame.timestamp += monotonicTimeDelta; + } + for (const video of context.videos || []) + video.timestamp += monotonicTimeDelta; + for (const screenshot4 of context.screenshots || []) + screenshot4.timestamp += monotonicTimeDelta; + for (const ariaSnapshot of context.ariaSnapshots || []) + ariaSnapshot.timestamp += monotonicTimeDelta; + for (const resource of context.resources) { + if (resource._monotonicTime) + resource._monotonicTime += monotonicTimeDelta; + } +} +function buildActionTree(actions) { + const itemMap = /* @__PURE__ */ new Map(); + for (const action of actions) { + itemMap.set(action.callId, { + id: action.callId, + parent: void 0, + children: [], + action + }); + } + const rootItem = { action: { ...kFakeRootAction }, id: "", parent: void 0, children: [] }; + for (const item of itemMap.values()) { + rootItem.action.startTime = Math.min(rootItem.action.startTime, item.action.startTime); + rootItem.action.endTime = Math.max(rootItem.action.endTime, item.action.endTime); + const parent = item.action.parentId ? itemMap.get(item.action.parentId) || rootItem : rootItem; + parent.children.push(item); + item.parent = parent; + } + const inheritStack = (item) => { + for (const child of item.children) { + child.action.stack = child.action.stack ?? item.action.stack; + inheritStack(child); + } + }; + inheritStack(rootItem); + return { rootItem, itemMap }; +} +function previousActionByEndTime(action) { + return action[prevByEndTimeSymbol]; +} +function nextActionByStartTime(action) { + return action[nextByStartTimeSymbol]; +} +function collectSources(actions, errorDescriptors) { + const result2 = /* @__PURE__ */ new Map(); + for (const action of actions) { + for (const frame of action.stack || []) { + let source14 = result2.get(frame.file); + if (!source14) { + source14 = { errors: [], content: void 0 }; + result2.set(frame.file, source14); + } + } + } + for (const error of errorDescriptors) { + const { action, stack, message } = error; + if (!action || !stack) + continue; + result2.get(stack[0].file)?.errors.push({ + line: stack[0].line || 0, + message + }); + } + return result2; +} +var prevByEndTimeSymbol, nextByStartTimeSymbol, TraceModel, kFakeRootAction; +var init_traceModel = __esm({ + "packages/isomorphic/trace/traceModel.ts"() { + "use strict"; + init_protocolFormatter(); + prevByEndTimeSymbol = /* @__PURE__ */ Symbol("prevByEndTime"); + nextByStartTimeSymbol = /* @__PURE__ */ Symbol("nextByStartTime"); + TraceModel = class { + constructor(traceUri, contexts) { + this.resourceOwnerRefToTitle = /* @__PURE__ */ new Map(); + this._eventsForAction = /* @__PURE__ */ new Map(); + this._screenshots = /* @__PURE__ */ new Map(); + this._ariaSnapshots = /* @__PURE__ */ new Map(); + this._domSnapshots = /* @__PURE__ */ new Set(); + const libraryContext = contexts.find((context) => context.origin === "library"); + this.traceUri = traceUri; + this.browserName = libraryContext?.browserName || ""; + this.sdkLanguage = libraryContext?.sdkLanguage; + this.channel = libraryContext?.channel; + this.testIdAttributeName = libraryContext?.testIdAttributeName; + this.platform = libraryContext?.platform || ""; + this.playwrightVersion = contexts.find((c) => c.playwrightVersion)?.playwrightVersion; + this.title = libraryContext?.title || ""; + this.options = libraryContext?.options || {}; + this.testTimeout = contexts.find((c) => c.origin === "testRunner")?.testTimeout; + this.annotations = contexts.find((c) => c.origin === "testRunner")?.annotations; + this.actions = mergeActionsAndUpdateTiming(contexts); + this.pages = [].concat(...contexts.map((c) => c.pages)); + this.videos = []; + this.wallTime = contexts.map((c) => c.wallTime).reduce((prev, cur) => Math.min(prev || Number.MAX_VALUE, cur), Number.MAX_VALUE); + this.startTime = contexts.map((c) => c.startTime).reduce((prev, cur) => Math.min(prev, cur), Number.MAX_VALUE); + this.endTime = contexts.map((c) => c.endTime).reduce((prev, cur) => Math.max(prev, cur), Number.MIN_VALUE); + this.events = [].concat(...contexts.map((c) => c.events)); + this.stdio = [].concat(...contexts.map((c) => c.stdio)); + this.errors = [].concat(...contexts.map((c) => c.errors)); + this.hasSource = contexts.some((c) => c.hasSource); + this.hasStepData = contexts.some((context) => context.origin === "testRunner"); + this.resources = []; + for (let i = 0; i < contexts.length; ++i) { + for (const entry of contexts[i].resources) + this.resources.push({ ...entry, id: `${resourceOwnerRef(entry) ?? i}-${entry.startedDateTime}-${entry.request.url}` }); + } + for (const context of contexts) { + for (const event of context.screenshots || []) + this._screenshots.set(`${event.callId}/${event.phase}`, event); + for (const event of context.ariaSnapshots || []) + this._ariaSnapshots.set(`${event.callId}/${event.phase}`, event); + for (const entry of context.domSnapshots || []) + this._domSnapshots.add(`${entry.callId}/${entry.phase}`); + this.videos.push(...context.videos || []); + } + this.hasDomSnapshots = !!this._domSnapshots.size; + this.hasAriaSnapshots = !!this._screenshots.size || !!this._ariaSnapshots.size; + this.attachments = this.actions.flatMap((action) => action.attachments?.map((attachment) => ({ ...attachment, callId: action.callId, traceUri })) ?? []); + this.visibleAttachments = this.attachments.filter((attachment) => !attachment.name.startsWith("_")); + this.pages.forEach((page, index) => this.resourceOwnerRefToTitle.set(page.pageId, "page#" + (index + 1))); + this.events.sort((a1, a2) => a1.time - a2.time); + this.resources.sort((a1, a2) => a1._monotonicTime - a2._monotonicTime); + let serviceWorkerCount = 0; + let apiRequestCount = 0; + for (const resource of this.resources) { + if (resource._serviceWorkerRef && !this.resourceOwnerRefToTitle.has(resource._serviceWorkerRef)) + this.resourceOwnerRefToTitle.set(resource._serviceWorkerRef, `service-worker#${++serviceWorkerCount}`); + if (resource._apiRequestRef && !this.resourceOwnerRefToTitle.has(resource._apiRequestRef)) + this.resourceOwnerRefToTitle.set(resource._apiRequestRef, `api#${++apiRequestCount}`); + } + this.errorDescriptors = this.hasStepData ? this._errorDescriptorsFromTestRunner() : this._errorDescriptorsFromActions(); + this.sources = collectSources(this.actions, this.errorDescriptors); + this.actionCounters = /* @__PURE__ */ new Map(); + for (const action of this.actions) { + action.group = action.group ?? getActionGroup({ type: action.class, method: action.method }); + if (action.group) + this.actionCounters.set(action.group, 1 + (this.actionCounters.get(action.group) || 0)); + } + } + createRelativeUrl(path66) { + const url3 = new URL("http://localhost/" + path66); + url3.searchParams.set("trace", this.traceUri); + return url3.toString().substring("http://localhost/".length); + } + failedAction() { + return this.actions.findLast((a) => a.error); + } + screenshotForCall(callId, phase) { + return this._screenshots.get(`${callId}/${phase}`); + } + hasDomSnapshotForCall(callId, phase) { + return this._domSnapshots.has(`${callId}/${phase}`); + } + ariaSnapshotForCall(callId, phase) { + return this._ariaSnapshots.get(`${callId}/${phase}`); + } + eventsForAction(action) { + let result2 = this._eventsForAction.get(action); + if (result2) + return result2; + let nextAction = nextActionByStartTime(action); + while (nextAction && nextAction.class === "Route") + nextAction = nextActionByStartTime(nextAction); + result2 = this.events.filter((event) => { + return event.time >= action.startTime && (!nextAction || event.time < nextAction.startTime); + }); + this._eventsForAction.set(action, result2); + return result2; + } + stats(action) { + let errors = 0; + let warnings = 0; + for (const event of this.eventsForAction(action)) { + if (event.type === "console") { + const type3 = event.messageType; + if (type3 === "warning") + ++warnings; + else if (type3 === "error") + ++errors; + } + if (event.type === "event" && event.method === "pageError") + ++errors; + } + return { errors, warnings }; + } + filteredActions(actionsFilter) { + const filter2 = new Set(actionsFilter); + return this.actions.filter((action) => !action.group || filter2.has(action.group)); + } + renderActionTree(filter2) { + const actions = this.filteredActions(filter2 ?? []); + const { rootItem } = buildActionTree(actions); + const actionTree = []; + const visit = (actionItem, indent2) => { + const title = renderFullTitleForCall({ ...actionItem.action, type: actionItem.action.class }); + actionTree.push(`${indent2}${title || actionItem.id}`); + for (const child of actionItem.children) + visit(child, indent2 + " "); + }; + rootItem.children.forEach((a) => visit(a, "")); + return actionTree; + } + _errorDescriptorsFromActions() { + const errors = []; + for (const action of this.actions || []) { + if (!action.error?.message) + continue; + errors.push({ + action, + stack: action.stack, + message: action.error.message + }); + } + return errors; + } + _errorDescriptorsFromTestRunner() { + return this.errors.filter((e) => !!e.message).map((error, i) => ({ + stack: error.stack, + message: error.message + })); + } + }; + kFakeRootAction = { + type: "action", + callId: "", + startTime: 0, + endTime: 0, + class: "", + method: "", + params: {}, + log: [] + }; + } +}); + +// packages/isomorphic/index.ts +var isomorphic_exports = {}; +__export(isomorphic_exports, { + CSharpLocatorFactory: () => CSharpLocatorFactory, + DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT: () => DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT, + DEFAULT_PLAYWRIGHT_TIMEOUT: () => DEFAULT_PLAYWRIGHT_TIMEOUT, + InvalidSelectorError: () => InvalidSelectorError, + JavaLocatorFactory: () => JavaLocatorFactory, + JavaScriptLocatorFactory: () => JavaScriptLocatorFactory, + JsonlLocatorFactory: () => JsonlLocatorFactory, + KeyParser: () => KeyParser, + LongStandingScope: () => LongStandingScope, + ManualPromise: () => ManualPromise, + MultiMap: () => MultiMap, + ParserError: () => ParserError, + PythonLocatorFactory: () => PythonLocatorFactory, + Semaphore: () => Semaphore, + SnapshotServer: () => SnapshotServer, + SnapshotStorage: () => SnapshotStorage, + TraceLoader: () => TraceLoader, + TraceModel: () => TraceModel, + ansiRegex: () => ansiRegex, + asLocator: () => asLocator, + asLocatorDescription: () => asLocatorDescription, + asLocators: () => asLocators, + assert: () => assert, + base64ByteLength: () => base64ByteLength, + buildActionTree: () => buildActionTree, + bytesToString: () => bytesToString, + cacheNormalizedWhitespaces: () => cacheNormalizedWhitespaces, + constructURLBasedOnBaseURL: () => constructURLBasedOnBaseURL, + createCallIdGenerator: () => createCallIdGenerator, + customCSSNames: () => customCSSNames, + deserializeURLMatch: () => deserializeURLMatch, + escapeForAttributeSelector: () => escapeForAttributeSelector, + escapeForTextSelector: () => escapeForTextSelector, + escapeHTML: () => escapeHTML, + escapeHTMLAttribute: () => escapeHTMLAttribute, + escapeRegExp: () => escapeRegExp, + escapeTemplateString: () => escapeTemplateString, + escapeWithQuotes: () => escapeWithQuotes, + findNewNode: () => findNewNode, + formatObject: () => formatObject, + formatObjectOrVoid: () => formatObjectOrVoid, + formatProtocolParam: () => formatProtocolParam, + getActionGroup: () => getActionGroup, + getExtensionForMimeType: () => getExtensionForMimeType, + getMetainfo: () => getMetainfo, + getMimeTypeForPath: () => getMimeTypeForPath, + globToRegexPattern: () => globToRegexPattern, + hasPointerCursor: () => hasPointerCursor, + headersArrayToObject: () => headersArrayToObject, + headersObjectToArray: () => headersObjectToArray, + isError: () => isError, + isHttpUrl: () => isHttpUrl, + isInvalidSelectorError: () => isInvalidSelectorError, + isJsonMimeType: () => isJsonMimeType, + isObject: () => isObject, + isRegExp: () => isRegExp2, + isRegexString: () => isRegexString, + isString: () => isString, + isTextualMimeType: () => isTextualMimeType, + isURLPattern: () => isURLPattern, + isXmlMimeType: () => isXmlMimeType, + kAnyFrameSelector: () => kAnyFrameSelector, + kCoverageStashError: () => kCoverageStashError, + kCoverageStashPrefix: () => kCoverageStashPrefix, + legacyCallId: () => legacyCallId, + locatorCustomDescription: () => locatorCustomDescription, + locatorOrSelectorAsSelector: () => locatorOrSelectorAsSelector, + longestCommonSubstring: () => longestCommonSubstring, + mergeIstanbulCoverage: () => mergeIstanbulCoverage, + methodMetainfo: () => methodMetainfo, + monotonicTime: () => monotonicTime, + msToString: () => msToString, + nextActionByStartTime: () => nextActionByStartTime, + noColors: () => noColors, + normalizeEscapedRegexQuotes: () => normalizeEscapedRegexQuotes, + normalizeWhiteSpace: () => normalizeWhiteSpace, + padImageToSize: () => padImageToSize, + parseAriaSnapshot: () => parseAriaSnapshot, + parseAriaSnapshotUnsafe: () => parseAriaSnapshotUnsafe, + parseAttributeSelector: () => parseAttributeSelector, + parseCSS: () => parseCSS, + parseClientSideCallMetadata: () => parseClientSideCallMetadata, + parseRegex: () => parseRegex, + parseSelector: () => parseSelector, + pollAgainstDeadline: () => pollAgainstDeadline, + previousActionByEndTime: () => previousActionByEndTime, + quoteCSSAttributeValue: () => quoteCSSAttributeValue, + raceAgainstDeadline: () => raceAgainstDeadline, + regexFlagNames: () => regexFlagNames, + renderAriaSnapshotAsYaml: () => renderAriaSnapshotAsYaml, + renderFullTitleForCall: () => renderFullTitleForCall, + renderParamsForCall: () => renderParamsForCall, + renderSubtitleForCall: () => renderSubtitleForCall, + renderTitleForCall: () => renderTitleForCall, + resolveGlobToRegexPattern: () => resolveGlobToRegexPattern, + resourceOwnerRef: () => resourceOwnerRef, + scaleImageToSize: () => scaleImageToSize, + serializeClientSideCallMetadata: () => serializeClientSideCallMetadata, + serializeSelector: () => serializeSelector, + serializeURLMatch: () => serializeURLMatch, + serializeURLPattern: () => serializeURLPattern, + setTimeOrigin: () => setTimeOrigin, + signalToPromise: () => signalToPromise, + sortedIstanbulCoverage: () => sortedIstanbulCoverage, + splitSelectorByFrame: () => splitSelectorByFrame, + splitSetCookieHeader: () => splitSetCookieHeader, + stringifySelector: () => stringifySelector, + stripAnsiEscapes: () => stripAnsiEscapes, + takeBranchCounters: () => takeBranchCounters, + takeCounters: () => takeCounters, + textValue: () => textValue, + timeOrigin: () => timeOrigin, + toSnakeCase: () => toSnakeCase, + toTitleCase: () => toTitleCase, + tomlArray: () => tomlArray, + tomlBasicString: () => tomlBasicString, + tomlMultilineBasicString: () => tomlMultilineBasicString, + trimString: () => trimString, + trimStringWithEllipsis: () => trimStringWithEllipsis, + truncateDataUrl: () => truncateDataUrl, + truncateParam: () => truncateParam, + unsafeLocatorOrSelectorAsSelector: () => unsafeLocatorOrSelectorAsSelector, + urlMatches: () => urlMatches, + urlMatchesEqual: () => urlMatchesEqual, + validate: () => validate, + visitAllSelectorParts: () => visitAllSelectorParts, + webColors: () => webColors, + yamlEscapeKeyIfNeeded: () => yamlEscapeKeyIfNeeded, + yamlEscapeValueIfNeeded: () => yamlEscapeValueIfNeeded +}); +var init_isomorphic = __esm({ + "packages/isomorphic/index.ts"() { + "use strict"; + init_ariaSnapshot(); + init_ariaSnapshotRenderer(); + init_assert(); + init_base64(); + init_colors(); + init_headers(); + init_imageUtils(); + init_istanbulCoverage(); + init_jsonSchema(); + init_locatorGenerators(); + init_manualPromise(); + init_mimeType(); + init_multimap(); + init_protocolFormatter(); + init_protocolMetainfo(); + init_rtti(); + init_semaphore(); + init_stringUtils(); + init_formatUtils(); + init_time(); + init_timeoutRunner(); + init_snapshotServer(); + init_urlMatch(); + init_cssParser(); + init_locatorParser(); + init_selectorParser(); + init_snapshotStorage(); + init_traceLoader(); + init_traceModel(); + init_traceUtils(); + init_yaml(); + } +}); + +// packages/utils/ascii.ts +function wrapInASCIIBox(text2, padding = 0) { + const lines = text2.split("\n"); + const maxLength = Math.max(...lines.map((line) => line.length)); + return [ + "\u2554" + "\u2550".repeat(maxLength + padding * 2) + "\u2557", + ...lines.map((line) => "\u2551" + " ".repeat(padding) + line + " ".repeat(maxLength - line.length + padding) + "\u2551"), + "\u255A" + "\u2550".repeat(maxLength + padding * 2) + "\u255D" + ].join("\n"); +} +function jsonStringifyForceASCII(object) { + return JSON.stringify(object).replace( + /[\u007f-\uffff]/g, + (c) => "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4) + ); +} +var init_ascii = __esm({ + "packages/utils/ascii.ts"() { + "use strict"; + } +}); + +// packages/utils/chromiumChannels.ts +function defaultUserDataDirForChannel(channel) { + return channelToDefaultUserDataDir.get(channel)?.[process.platform]; +} +function isChromiumChannelName(channel) { + return channelToDefaultUserDataDir.has(channel); +} +var import_os, import_path, channelToDefaultUserDataDir; +var init_chromiumChannels = __esm({ + "packages/utils/chromiumChannels.ts"() { + "use strict"; + import_os = __toESM(require("os")); + import_path = __toESM(require("path")); + channelToDefaultUserDataDir = /* @__PURE__ */ new Map([ + ["chrome", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome", "User Data") + }], + ["chrome-beta", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-beta"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Beta"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Beta", "User Data") + }], + ["chrome-dev", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-unstable"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Dev"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Dev", "User Data") + }], + ["chrome-canary", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-canary"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Canary"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome SxS", "User Data") + }], + ["msedge", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge", "User Data") + }], + ["msedge-beta", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-beta"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Beta"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Beta", "User Data") + }], + ["msedge-dev", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-dev"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Dev"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Dev", "User Data") + }], + ["msedge-canary", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-canary"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Canary"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge SxS", "User Data") + }] + ]); + } +}); + +// packages/utils/third_party/pixelmatch.js +var require_pixelmatch = __commonJS({ + "packages/utils/third_party/pixelmatch.js"(exports2, module3) { + "use strict"; + module3.exports = pixelmatch2; + var defaultOptions = { + threshold: 0.1, + // matching threshold (0 to 1); smaller is more sensitive + includeAA: false, + // whether to skip anti-aliasing detection + alpha: 0.1, + // opacity of original image in diff output + aaColor: [255, 255, 0], + // color of anti-aliased pixels in diff output + diffColor: [255, 0, 0], + // color of different pixels in diff output + diffColorAlt: null, + // whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two + diffMask: false + // draw the diff over a transparent background (a mask) + }; + function pixelmatch2(img1, img2, output, width, height, options) { + if (!isPixelData(img1) || !isPixelData(img2) || output && !isPixelData(output)) + throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected."); + if (img1.length !== img2.length || output && output.length !== img1.length) + throw new Error("Image sizes do not match."); + if (img1.length !== width * height * 4) throw new Error("Image data size does not match width/height."); + options = Object.assign({}, defaultOptions, options); + const len = width * height; + const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len); + const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len); + let identical = true; + for (let i = 0; i < len; i++) { + if (a32[i] !== b32[i]) { + identical = false; + break; + } + } + if (identical) { + if (output && !options.diffMask) { + for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options.alpha, output); + } + return 0; + } + const maxDelta = 35215 * options.threshold * options.threshold; + let diff2 = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const pos = (y * width + x) * 4; + const delta = colorDelta(img1, img2, pos, pos); + if (Math.abs(delta) > maxDelta) { + if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) { + if (output && !options.diffMask) drawPixel2(output, pos, ...options.aaColor); + } else { + if (output) { + drawPixel2(output, pos, ...delta < 0 && options.diffColorAlt || options.diffColor); + } + diff2++; + } + } else if (output) { + if (!options.diffMask) drawGrayPixel(img1, pos, options.alpha, output); + } + } + } + return diff2; + } + function isPixelData(arr) { + return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1; + } + function antialiased(img, x1, y1, width, height, img2) { + const x0 = Math.max(x1 - 1, 0); + const y0 = Math.max(y1 - 1, 0); + const x2 = Math.min(x1 + 1, width - 1); + const y2 = Math.min(y1 + 1, height - 1); + const pos = (y1 * width + x1) * 4; + let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; + let min = 0; + let max = 0; + let minX, minY, maxX, maxY; + for (let x = x0; x <= x2; x++) { + for (let y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + const delta = colorDelta(img, img, pos, (y * width + x) * 4, true); + if (delta === 0) { + zeroes++; + if (zeroes > 2) return false; + } else if (delta < min) { + min = delta; + minX = x; + minY = y; + } else if (delta > max) { + max = delta; + maxX = x; + maxY = y; + } + } + } + if (min === 0 || max === 0) return false; + return hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height) || hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height); + } + function hasManySiblings(img, x1, y1, width, height) { + const x0 = Math.max(x1 - 1, 0); + const y0 = Math.max(y1 - 1, 0); + const x2 = Math.min(x1 + 1, width - 1); + const y2 = Math.min(y1 + 1, height - 1); + const pos = (y1 * width + x1) * 4; + let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; + for (let x = x0; x <= x2; x++) { + for (let y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + const pos2 = (y * width + x) * 4; + if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++; + if (zeroes > 2) return true; + } + } + return false; + } + function colorDelta(img1, img2, k, m, yOnly) { + let r1 = img1[k + 0]; + let g1 = img1[k + 1]; + let b1 = img1[k + 2]; + let a1 = img1[k + 3]; + let r2 = img2[m + 0]; + let g2 = img2[m + 1]; + let b2 = img2[m + 2]; + let a2 = img2[m + 3]; + if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0; + if (a1 < 255) { + a1 /= 255; + r1 = blend(r1, a1); + g1 = blend(g1, a1); + b1 = blend(b1, a1); + } + if (a2 < 255) { + a2 /= 255; + r2 = blend(r2, a2); + g2 = blend(g2, a2); + b2 = blend(b2, a2); + } + const y1 = rgb2y(r1, g1, b1); + const y2 = rgb2y(r2, g2, b2); + const y = y1 - y2; + if (yOnly) return y; + const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2); + const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2); + const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q; + return y1 > y2 ? -delta : delta; + } + function rgb2y(r, g, b) { + return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; + } + function rgb2i(r, g, b) { + return r * 0.59597799 - g * 0.2741761 - b * 0.32180189; + } + function rgb2q(r, g, b) { + return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; + } + function blend(c, a) { + return 255 + (c - 255) * a; + } + function drawPixel2(output, pos, r, g, b) { + output[pos + 0] = r; + output[pos + 1] = g; + output[pos + 2] = b; + output[pos + 3] = 255; + } + function drawGrayPixel(img, i, alpha, output) { + const r = img[i + 0]; + const g = img[i + 1]; + const b = img[i + 2]; + const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255); + drawPixel2(output, i, val, val, val); + } + } +}); + +// packages/utils/image_tools/colorUtils.ts +function blendWithWhite(c, a) { + return 255 + (c - 255) * a; +} +function rgb2gray(r, g, b) { + return 77 * r + 150 * g + 29 * b + 128 >> 8; +} +function colorDeltaE94(rgb1, rgb2) { + const [l1, a1, b1] = xyz2lab(srgb2xyz(rgb1)); + const [l2, a2, b2] = xyz2lab(srgb2xyz(rgb2)); + const deltaL = l1 - l2; + const deltaA = a1 - a2; + const deltaB = b1 - b2; + const c1 = Math.sqrt(a1 ** 2 + b1 ** 2); + const c2 = Math.sqrt(a2 ** 2 + b2 ** 2); + const deltaC = c1 - c2; + let deltaH = deltaA ** 2 + deltaB ** 2 - deltaC ** 2; + deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH); + const k1 = 0.045; + const k2 = 0.015; + const kL = 1; + const kC = 1; + const kH = 1; + const sC = 1 + k1 * c1; + const sH = 1 + k2 * c1; + const sL = 1; + return Math.sqrt((deltaL / sL / kL) ** 2 + (deltaC / sC / kC) ** 2 + (deltaH / sH / kH) ** 2); +} +function srgb2xyz(rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + return [ + r * 0.4124 + g * 0.3576 + b * 0.1805, + r * 0.2126 + g * 0.7152 + b * 0.0722, + r * 0.0193 + g * 0.1192 + b * 0.9505 + ]; +} +function xyz2lab(xyz) { + const x = xyz[0] / 0.950489; + const y = xyz[1]; + const z35 = xyz[2] / 1.08884; + const fx = x > sigma_pow3 ? x ** (1 / 3) : x / 3 / sigma_pow2 + 4 / 29; + const fy = y > sigma_pow3 ? y ** (1 / 3) : y / 3 / sigma_pow2 + 4 / 29; + const fz = z35 > sigma_pow3 ? z35 ** (1 / 3) : z35 / 3 / sigma_pow2 + 4 / 29; + const l = 116 * fy - 16; + const a = 500 * (fx - fy); + const b = 200 * (fy - fz); + return [l, a, b]; +} +var sigma_pow2, sigma_pow3; +var init_colorUtils = __esm({ + "packages/utils/image_tools/colorUtils.ts"() { + "use strict"; + sigma_pow2 = 6 * 6 / 29 / 29; + sigma_pow3 = 6 * 6 * 6 / 29 / 29 / 29; + } +}); + +// packages/utils/image_tools/imageChannel.ts +var ImageChannel; +var init_imageChannel = __esm({ + "packages/utils/image_tools/imageChannel.ts"() { + "use strict"; + init_colorUtils(); + ImageChannel = class _ImageChannel { + static intoRGB(width, height, data, options = {}) { + const { + paddingSize = 0, + paddingColorOdd = [255, 0, 255], + paddingColorEven = [0, 255, 0] + } = options; + const newWidth = width + 2 * paddingSize; + const newHeight = height + 2 * paddingSize; + const r = new Uint8Array(newWidth * newHeight); + const g = new Uint8Array(newWidth * newHeight); + const b = new Uint8Array(newWidth * newHeight); + for (let y = 0; y < newHeight; ++y) { + for (let x = 0; x < newWidth; ++x) { + const index = y * newWidth + x; + if (y >= paddingSize && y < newHeight - paddingSize && x >= paddingSize && x < newWidth - paddingSize) { + const offset = ((y - paddingSize) * width + (x - paddingSize)) * 4; + const alpha = data[offset + 3] === 255 ? 1 : data[offset + 3] / 255; + r[index] = blendWithWhite(data[offset], alpha); + g[index] = blendWithWhite(data[offset + 1], alpha); + b[index] = blendWithWhite(data[offset + 2], alpha); + } else { + const color = (y + x) % 2 === 0 ? paddingColorEven : paddingColorOdd; + r[index] = color[0]; + g[index] = color[1]; + b[index] = color[2]; + } + } + } + return [ + new _ImageChannel(newWidth, newHeight, r), + new _ImageChannel(newWidth, newHeight, g), + new _ImageChannel(newWidth, newHeight, b) + ]; + } + constructor(width, height, data) { + this.data = data; + this.width = width; + this.height = height; + } + get(x, y) { + return this.data[y * this.width + x]; + } + boundXY(x, y) { + return [ + Math.min(Math.max(x, 0), this.width - 1), + Math.min(Math.max(y, 0), this.height - 1) + ]; + } + }; + } +}); + +// packages/utils/image_tools/stats.ts +function ssim(stats, x1, y1, x2, y2) { + const mean1 = stats.meanC1(x1, y1, x2, y2); + const mean2 = stats.meanC2(x1, y1, x2, y2); + const var1 = stats.varianceC1(x1, y1, x2, y2); + const var2 = stats.varianceC2(x1, y1, x2, y2); + const cov = stats.covariance(x1, y1, x2, y2); + const c1 = (0.01 * DYNAMIC_RANGE) ** 2; + const c2 = (0.03 * DYNAMIC_RANGE) ** 2; + return (2 * mean1 * mean2 + c1) * (2 * cov + c2) / (mean1 ** 2 + mean2 ** 2 + c1) / (var1 + var2 + c2); +} +var DYNAMIC_RANGE, FastStats; +var init_stats = __esm({ + "packages/utils/image_tools/stats.ts"() { + "use strict"; + DYNAMIC_RANGE = 2 ** 8 - 1; + FastStats = class { + constructor(c1, c2) { + this.c1 = c1; + this.c2 = c2; + const { width, height } = c1; + this._partialSumC1 = new Array(width * height); + this._partialSumC2 = new Array(width * height); + this._partialSumSq1 = new Array(width * height); + this._partialSumSq2 = new Array(width * height); + this._partialSumMult = new Array(width * height); + const recalc = (mx, idx, initial, x, y) => { + mx[idx] = initial; + if (y > 0) + mx[idx] += mx[(y - 1) * width + x]; + if (x > 0) + mx[idx] += mx[y * width + x - 1]; + if (x > 0 && y > 0) + mx[idx] -= mx[(y - 1) * width + x - 1]; + }; + for (let y = 0; y < height; ++y) { + for (let x = 0; x < width; ++x) { + const idx = y * width + x; + recalc(this._partialSumC1, idx, this.c1.data[idx], x, y); + recalc(this._partialSumC2, idx, this.c2.data[idx], x, y); + recalc(this._partialSumSq1, idx, this.c1.data[idx] * this.c1.data[idx], x, y); + recalc(this._partialSumSq2, idx, this.c2.data[idx] * this.c2.data[idx], x, y); + recalc(this._partialSumMult, idx, this.c1.data[idx] * this.c2.data[idx], x, y); + } + } + } + _sum(partialSum, x1, y1, x2, y2) { + const width = this.c1.width; + let result2 = partialSum[y2 * width + x2]; + if (y1 > 0) + result2 -= partialSum[(y1 - 1) * width + x2]; + if (x1 > 0) + result2 -= partialSum[y2 * width + x1 - 1]; + if (x1 > 0 && y1 > 0) + result2 += partialSum[(y1 - 1) * width + x1 - 1]; + return result2; + } + meanC1(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return this._sum(this._partialSumC1, x1, y1, x2, y2) / N; + } + meanC2(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return this._sum(this._partialSumC2, x1, y1, x2, y2) / N; + } + varianceC1(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumSq1, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) ** 2 / N) / N; + } + varianceC2(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumSq2, x1, y1, x2, y2) - this._sum(this._partialSumC2, x1, y1, x2, y2) ** 2 / N) / N; + } + covariance(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumMult, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) * this._sum(this._partialSumC2, x1, y1, x2, y2) / N) / N; + } + }; + } +}); + +// packages/utils/image_tools/compare.ts +function drawPixel(width, data, x, y, r, g, b) { + const idx = (y * width + x) * 4; + data[idx + 0] = r; + data[idx + 1] = g; + data[idx + 2] = b; + data[idx + 3] = 255; +} +function compare(actual, expected, diff2, width, height, options = {}) { + const { + maxColorDeltaE94 = 1 + } = options; + const paddingSize = Math.max(VARIANCE_WINDOW_RADIUS, SSIM_WINDOW_RADIUS); + const paddingColorEven = [255, 0, 255]; + const paddingColorOdd = [0, 255, 0]; + const [r1, g1, b1] = ImageChannel.intoRGB(width, height, expected, { + paddingSize, + paddingColorEven, + paddingColorOdd + }); + const [r2, g2, b2] = ImageChannel.intoRGB(width, height, actual, { + paddingSize, + paddingColorEven, + paddingColorOdd + }); + const noop = (x, y) => { + }; + const drawRedPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 0, 0) : noop; + const drawYellowPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 255, 0) : noop; + const drawGrayPixel = diff2 ? (x, y) => { + const gray = rgb2gray(r1.get(x, y), g1.get(x, y), b1.get(x, y)); + const value2 = blendWithWhite(gray, 0.1); + drawPixel(width, diff2, x - paddingSize, y - paddingSize, value2, value2, value2); + } : noop; + let fastR; + let fastG; + let fastB; + let diffCount = 0; + for (let y = paddingSize; y < r1.height - paddingSize; ++y) { + for (let x = paddingSize; x < r1.width - paddingSize; ++x) { + if (r1.get(x, y) === r2.get(x, y) && g1.get(x, y) === g2.get(x, y) && b1.get(x, y) === b2.get(x, y)) { + drawGrayPixel(x, y); + continue; + } + const delta = colorDeltaE94( + [r1.get(x, y), g1.get(x, y), b1.get(x, y)], + [r2.get(x, y), g2.get(x, y), b2.get(x, y)] + ); + if (delta <= maxColorDeltaE94) { + drawGrayPixel(x, y); + continue; + } + if (!fastR || !fastG || !fastB) { + fastR = new FastStats(r1, r2); + fastG = new FastStats(g1, g2); + fastB = new FastStats(b1, b2); + } + const [varX1, varY1] = r1.boundXY(x - VARIANCE_WINDOW_RADIUS, y - VARIANCE_WINDOW_RADIUS); + const [varX2, varY2] = r1.boundXY(x + VARIANCE_WINDOW_RADIUS, y + VARIANCE_WINDOW_RADIUS); + const var1 = fastR.varianceC1(varX1, varY1, varX2, varY2) + fastG.varianceC1(varX1, varY1, varX2, varY2) + fastB.varianceC1(varX1, varY1, varX2, varY2); + const var2 = fastR.varianceC2(varX1, varY1, varX2, varY2) + fastG.varianceC2(varX1, varY1, varX2, varY2) + fastB.varianceC2(varX1, varY1, varX2, varY2); + if (var1 === 0 || var2 === 0) { + drawRedPixel(x, y); + ++diffCount; + continue; + } + const [ssimX1, ssimY1] = r1.boundXY(x - SSIM_WINDOW_RADIUS, y - SSIM_WINDOW_RADIUS); + const [ssimX2, ssimY2] = r1.boundXY(x + SSIM_WINDOW_RADIUS, y + SSIM_WINDOW_RADIUS); + const ssimRGB = (ssim(fastR, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastG, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastB, ssimX1, ssimY1, ssimX2, ssimY2)) / 3; + const isAntialiased = ssimRGB >= 0.99; + if (isAntialiased) { + drawYellowPixel(x, y); + } else { + drawRedPixel(x, y); + ++diffCount; + } + } + } + return diffCount; +} +var SSIM_WINDOW_RADIUS, VARIANCE_WINDOW_RADIUS; +var init_compare = __esm({ + "packages/utils/image_tools/compare.ts"() { + "use strict"; + init_colorUtils(); + init_imageChannel(); + init_stats(); + SSIM_WINDOW_RADIUS = 15; + VARIANCE_WINDOW_RADIUS = 1; + } +}); + +// packages/utils/webp/webp_codec.js +var require_webp_codec = __commonJS({ + "packages/utils/webp/webp_codec.js"(exports2, module3) { + "use strict"; + var Module = (() => { + var _scriptName = globalThis.document?.currentScript?.src; + return async function(moduleArg = {}) { + var Module2 = moduleArg; + var ENVIRONMENT_IS_WEB = !!globalThis.window; + var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope; + var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != "renderer"; + var programArgs = []; + var thisProgram = "./this.program"; + var quit_ = (status, toThrow) => { + throw toThrow; + }; + if (typeof __filename != "undefined") { + _scriptName = __filename; + } else { + } + var scriptDirectory = ""; + function locateFile(path66) { + if (Module2["locateFile"]) { + return Module2["locateFile"](path66, scriptDirectory); + } + return scriptDirectory + path66; + } + var readAsync, readBinary; + if (ENVIRONMENT_IS_NODE) { + var fs71 = require("node:fs"); + scriptDirectory = __dirname + "/"; + readBinary = (filename) => { + filename = isFileURI(filename) ? new URL(filename) : filename; + var ret = fs71.readFileSync(filename); + return ret; + }; + readAsync = async (filename, binary = true) => { + filename = isFileURI(filename) ? new URL(filename) : filename; + var ret = fs71.readFileSync(filename, binary ? void 0 : "utf8"); + return ret; + }; + if (process.argv.length > 1) { + thisProgram = process.argv[1].replace(/\\/g, "/"); + } + programArgs = process.argv.slice(2); + quit_ = (status, toThrow) => { + process.exitCode = status; + throw toThrow; + }; + } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + try { + scriptDirectory = new URL(".", _scriptName).href; + } catch { + } + { + readAsync = async (url3) => { + var response2 = await fetch(url3, { credentials: "same-origin" }); + if (response2.ok) { + return response2.arrayBuffer(); + } + throw new Error(response2.status + " : " + response2.url); + }; + } + } else { + } + var out = console.log.bind(console); + var err = console.error.bind(console); + var wasmBinary; + var ABORT = false; + var EXITSTATUS; + var isFileURI = (filename) => filename.startsWith("file://"); + class EmscriptenEH { + } + class EmscriptenSjLj extends EmscriptenEH { + } + var runtimeInitialized = false; + function getMemoryBuffer() { + try { + var b = wasmMemory.toResizableBuffer(); + return b; + } catch { + } + return wasmMemory.buffer; + } + function updateMemoryViews() { + if (HEAP8?.buffer?.resizable) return; + var b = getMemoryBuffer(); + HEAP8 = new Int8Array(b); + HEAP16 = new Int16Array(b); + Module2["HEAPU8"] = HEAPU8 = new Uint8Array(b); + HEAPU16 = new Uint16Array(b); + HEAP32 = new Int32Array(b); + Module2["HEAPU32"] = HEAPU32 = new Uint32Array(b); + HEAPF32 = new Float32Array(b); + HEAPF64 = new Float64Array(b); + HEAP64 = new BigInt64Array(b); + HEAPU64 = new BigUint64Array(b); + } + function preRun() { + var preRun2 = Module2["preRun"]; + if (preRun2) { + if (typeof preRun2 == "function") preRun2 = [preRun2]; + onPreRuns.push(...preRun2); + } + callRuntimeCallbacks(onPreRuns); + } + function initRuntime() { + runtimeInitialized = true; + wasmExports["g"](); + } + function postRun() { + var postRun2 = Module2["postRun"]; + if (postRun2) { + if (typeof postRun2 == "function") postRun2 = [postRun2]; + onPostRuns.push(...postRun2); + } + callRuntimeCallbacks(onPostRuns); + } + function abort(what) { + Module2["onAbort"]?.(what); + what = `Aborted(${what})`; + err(what); + ABORT = true; + what += ". Build with -sASSERTIONS for more info."; + var e = new WebAssembly.RuntimeError(what); + throw e; + } + var wasmBinaryFile; + function findWasmBinary() { + return locateFile("webp_codec.wasm"); + } + function getBinarySync(file) { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary); + } + if (readBinary) { + return readBinary(file); + } + throw 'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'; + } + function instantiateSync(file, info) { + var module4; + var binary = getBinarySync(file); + module4 = new WebAssembly.Module(binary); + var instance = new WebAssembly.Instance(module4, info); + return [instance, module4]; + } + function getWasmImports() { + var imports = { a: wasmImports }; + return imports; + } + function createWasm() { + function receiveInstance(instance) { + wasmExports = instance.exports; + assignWasmExports(wasmExports); + updateMemoryViews(); + return wasmExports; + } + var info = getWasmImports(); + var instantiateWasm = Module2["instantiateWasm"]; + if (instantiateWasm) { + return new Promise((resolve) => { + instantiateWasm(info, (inst) => resolve(receiveInstance(inst))); + }); + } + wasmBinaryFile ??= findWasmBinary(); + var result2 = instantiateSync(wasmBinaryFile, info); + return receiveInstance(result2[0]); + } + class ExitStatus { + name = "ExitStatus"; + constructor(status) { + this.message = `Program terminated with exit(${status})`; + this.status = status; + } + } + var HEAP16; + var HEAP32; + var HEAP64; + var HEAP8; + var HEAPF32; + var HEAPF64; + var HEAPU16; + var HEAPU32; + var HEAPU64; + var HEAPU8; + var callRuntimeCallbacks = (callbacks) => { + while (callbacks.length > 0) { + callbacks.shift()(Module2); + } + }; + var onPostRuns = []; + var onPreRuns = []; + var noExitRuntime = true; + var __abort_js = () => abort(""); + var runtimeKeepaliveCounter = 0; + var __emscripten_runtime_keepalive_clear = () => { + noExitRuntime = false; + runtimeKeepaliveCounter = 0; + }; + var timers = {}; + var handleException = (e) => { + if (e instanceof ExitStatus || e == "unwind") { + return EXITSTATUS; + } + quit_(1, e); + }; + var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0; + var _proc_exit = (code) => { + EXITSTATUS = code; + if (!keepRuntimeAlive()) { + Module2["onExit"]?.(code); + ABORT = true; + } + quit_(code, new ExitStatus(code)); + }; + var exitJS = (status, implicit) => { + EXITSTATUS = status; + _proc_exit(status); + }; + var _exit = exitJS; + var maybeExit = () => { + if (!keepRuntimeAlive()) { + try { + _exit(EXITSTATUS); + } catch (e) { + handleException(e); + } + } + }; + var callUserCallback = (func) => { + if (ABORT) { + return; + } + try { + return func(); + } catch (e) { + handleException(e); + } finally { + maybeExit(); + } + }; + var _emscripten_get_now = () => performance.now(); + var __setitimer_js = (which, timeout_ms) => { + if (timers[which]) { + clearTimeout(timers[which].id); + delete timers[which]; + } + if (!timeout_ms) return 0; + var id = setTimeout(() => { + delete timers[which]; + callUserCallback(() => __emscripten_timeout(which, _emscripten_get_now())); + }, timeout_ms); + timers[which] = { id, timeout_ms }; + return 0; + }; + var getHeapMax = () => 2147483648; + var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment; + var growMemory = (size) => { + var oldHeapSize = wasmMemory.buffer.byteLength; + var pages = (size - oldHeapSize + 65535) / 65536 | 0; + try { + wasmMemory.grow(pages); + updateMemoryViews(); + return 1; + } catch (e) { + } + }; + var _emscripten_resize_heap = (requestedSize) => { + var oldSize = HEAPU8.length; + requestedSize >>>= 0; + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + return false; + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = growMemory(newSize); + if (replacement) { + return true; + } + } + return false; + }; + { + if (Module2["noExitRuntime"]) noExitRuntime = Module2["noExitRuntime"]; + if (Module2["print"]) out = Module2["print"]; + if (Module2["printErr"]) err = Module2["printErr"]; + if (Module2["wasmBinary"]) wasmBinary = Module2["wasmBinary"]; + if (Module2["arguments"]) programArgs = Module2["arguments"]; + if (Module2["thisProgram"]) thisProgram = Module2["thisProgram"]; + var preInit = Module2["preInit"]; + if (preInit) { + if (typeof preInit == "function") Module2["preInit"] = preInit = [preInit]; + while (preInit.length > 0) { + preInit.shift()(); + } + } + } + var _webp_encode_rgba, _webp_decode_rgba, _webp_free, _malloc, _free, __emscripten_timeout, memory, __indirect_function_table, wasmMemory; + function assignWasmExports(wasmExports2) { + _webp_encode_rgba = Module2["_webp_encode_rgba"] = wasmExports2["h"]; + _webp_decode_rgba = Module2["_webp_decode_rgba"] = wasmExports2["i"]; + _webp_free = Module2["_webp_free"] = wasmExports2["j"]; + _malloc = Module2["_malloc"] = wasmExports2["k"]; + _free = Module2["_free"] = wasmExports2["l"]; + __emscripten_timeout = wasmExports2["m"]; + memory = wasmMemory = wasmExports2["f"]; + __indirect_function_table = wasmExports2["__indirect_function_table"]; + } + var wasmImports = { e: __abort_js, d: __emscripten_runtime_keepalive_clear, a: __setitimer_js, b: _emscripten_resize_heap, c: _proc_exit }; + async function run() { + preRun(); + var setStatus = Module2["setStatus"]; + if (setStatus) { + setStatus("Running..."); + await new Promise((resolve) => setTimeout(resolve, 1)); + setTimeout(setStatus, 1, ""); + } + if (ABORT) return; + initRuntime(); + Module2["onRuntimeInitialized"]?.(); + postRun(); + } + var wasmExports; + wasmExports = createWasm(); + await run(); + ; + return Module2; + }; + })(); + if (typeof exports2 === "object" && typeof module3 === "object") { + module3.exports = Module; + module3.exports.default = Module; + } else if (typeof define === "function" && define["amd"]) define([], () => Module); + } +}); + +// packages/utils/webp/webp.ts +function webpModule() { + if (!module2) { + const instance = { wasmBinary: import_fs.default.readFileSync(import_path2.default.join(__dirname, "webp_codec.wasm")) }; + (0, import_webp_codec.default)(instance); + module2 = instance; + } + return module2; +} +function encodeWebp(image, options = {}) { + const { quality = 75, lossless = false } = options; + const m = webpModule(); + const inPtr = m._malloc(image.data.length); + m.HEAPU8.set(image.data, inPtr); + const sizePtr = m._malloc(4); + const outPtr = m._webp_encode_rgba(inPtr, image.width, image.height, quality, lossless ? 1 : 0, sizePtr); + const size = m.HEAPU32[sizePtr >> 2]; + let out; + if (outPtr && size) { + out = Buffer.from(m.HEAPU8.subarray(outPtr, outPtr + size)); + m._webp_free(outPtr); + } + m._free(inPtr); + m._free(sizePtr); + if (!out) + throw new Error("WebP encode failed"); + return out; +} +function decodeWebp(buffer) { + const m = webpModule(); + const inPtr = m._malloc(buffer.length); + m.HEAPU8.set(buffer, inPtr); + const widthPtr = m._malloc(4); + const heightPtr = m._malloc(4); + const outPtr = m._webp_decode_rgba(inPtr, buffer.length, widthPtr, heightPtr); + const width = m.HEAPU32[widthPtr >> 2]; + const height = m.HEAPU32[heightPtr >> 2]; + let result2; + if (outPtr) { + const data = Buffer.from(m.HEAPU8.subarray(outPtr, outPtr + width * height * 4)); + result2 = { data, width, height }; + m._webp_free(outPtr); + } + m._free(inPtr); + m._free(widthPtr); + m._free(heightPtr); + if (!result2) + throw new Error("WebP decode failed"); + return result2; +} +function isLosslessWebp(buffer) { + if (buffer.length < 16 || buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WEBP") + return false; + let offset = 12; + while (offset + 8 <= buffer.length) { + const fourcc = buffer.toString("ascii", offset, offset + 4); + if (fourcc === "VP8L") + return true; + if (fourcc === "VP8 ") + return false; + const size = buffer.readUInt32LE(offset + 4); + offset += 8 + size + (size & 1); + } + return false; +} +var import_fs, import_path2, import_webp_codec, module2; +var init_webp = __esm({ + "packages/utils/webp/webp.ts"() { + "use strict"; + import_fs = __toESM(require("fs")); + import_path2 = __toESM(require("path")); + import_webp_codec = __toESM(require_webp_codec()); + } +}); + +// packages/utils/comparators.ts +function getComparator(mimeType) { + if (mimeType === "image/png") + return compareImages.bind(null, "image/png"); + if (mimeType === "image/jpeg") + return compareImages.bind(null, "image/jpeg"); + if (mimeType === "image/webp") + return compareImages.bind(null, "image/webp"); + if (mimeType === "text/plain") + return compareText; + return compareBuffersOrStrings; +} +function compareBuffersOrStrings(actualBuffer, expectedBuffer) { + if (typeof actualBuffer === "string") + return compareText(actualBuffer, expectedBuffer); + if (!actualBuffer || !(actualBuffer instanceof Buffer)) + return { errorMessage: "Actual result should be a Buffer or a string." }; + if (Buffer.compare(actualBuffer, expectedBuffer)) + return { errorMessage: "Buffers differ" }; + return null; +} +function compareImages(mimeType, actualBuffer, expectedBuffer, options = {}) { + if (!actualBuffer || !(actualBuffer instanceof Buffer)) + return { errorMessage: "Actual result should be a Buffer." }; + validateBuffer(expectedBuffer, mimeType); + const decode = (buffer) => { + if (mimeType === "image/png") + return PNG.sync.read(buffer); + if (mimeType === "image/webp") + return decodeWebp(buffer); + return jpegjs.decode(buffer, { maxMemoryUsageInMB: JPEG_JS_MAX_BUFFER_SIZE_IN_MB }); + }; + let actual = decode(actualBuffer); + let expected = decode(expectedBuffer); + const size = { width: Math.max(expected.width, actual.width), height: Math.max(expected.height, actual.height) }; + let sizesMismatchError = ""; + if (expected.width !== actual.width || expected.height !== actual.height) { + sizesMismatchError = `Expected an image ${expected.width}px by ${expected.height}px, received ${actual.width}px by ${actual.height}px. `; + actual = padImageToSize(actual, size); + expected = padImageToSize(expected, size); + } + const diff2 = new PNG({ width: size.width, height: size.height }); + let count; + if (options.comparator === "ssim-cie94") { + count = compare(expected.data, actual.data, diff2.data, size.width, size.height, { + // All ΔE* formulae are originally designed to have the difference of 1.0 stand for a "just noticeable difference" (JND). + // See https://en.wikipedia.org/wiki/Color_difference#CIELAB_%CE%94E* + maxColorDeltaE94: 1 + }); + } else if ((options.comparator ?? "pixelmatch") === "pixelmatch") { + count = (0, import_pixelmatch.default)(expected.data, actual.data, diff2.data, size.width, size.height, { + threshold: options.threshold ?? 0.2 + }); + } else { + throw new Error(`Configuration specifies unknown comparator "${options.comparator}"`); + } + const maxDiffPixels1 = options.maxDiffPixels; + const maxDiffPixels2 = options.maxDiffPixelRatio !== void 0 ? expected.width * expected.height * options.maxDiffPixelRatio : void 0; + let maxDiffPixels; + if (maxDiffPixels1 !== void 0 && maxDiffPixels2 !== void 0) + maxDiffPixels = Math.min(maxDiffPixels1, maxDiffPixels2); + else + maxDiffPixels = maxDiffPixels1 ?? maxDiffPixels2 ?? 0; + const ratio = Math.ceil(count / (expected.width * expected.height) * 100) / 100; + const pixelsMismatchError = count > maxDiffPixels ? `${count} pixels (ratio ${ratio.toFixed(2)} of all image pixels) are different.` : ""; + if (pixelsMismatchError || sizesMismatchError) + return { errorMessage: sizesMismatchError + pixelsMismatchError, diff: PNG.sync.write(diff2) }; + return null; +} +function validateBuffer(buffer, mimeType) { + if (mimeType === "image/png") { + const pngMagicNumber = [137, 80, 78, 71, 13, 10, 26, 10]; + if (buffer.length < pngMagicNumber.length || !pngMagicNumber.every((byte, index) => buffer[index] === byte)) + throw new Error("Could not decode expected image as PNG."); + } else if (mimeType === "image/jpeg") { + const jpegMagicNumber = [255, 216]; + if (buffer.length < jpegMagicNumber.length || !jpegMagicNumber.every((byte, index) => buffer[index] === byte)) + throw new Error("Could not decode expected image as JPEG."); + } else if (mimeType === "image/webp") { + if (buffer.length < 12 || buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WEBP") + throw new Error("Could not decode expected image as WEBP."); + } +} +function compareText(actual, expectedBuffer) { + if (typeof actual !== "string") + return { errorMessage: "Actual result should be a string" }; + let expected = expectedBuffer.toString("utf-8"); + if (expected === actual) + return null; + if (!actual.endsWith("\n")) + actual += "\n"; + if (!expected.endsWith("\n")) + expected += "\n"; + const lines = diff.createPatch("file", expected, actual, void 0, void 0, { context: 5 }).split("\n"); + const coloredLines = lines.slice(4).map((line) => { + if (line.startsWith("-")) + return colors.green(line); + if (line.startsWith("+")) + return colors.red(line); + if (line.startsWith("@@")) + return colors.dim(line); + return line; + }); + const errorMessage = coloredLines.join("\n"); + return { errorMessage }; +} +var import_pixelmatch, jpegjs, colors, diff, PNG, JPEG_JS_MAX_BUFFER_SIZE_IN_MB; +var init_comparators = __esm({ + "packages/utils/comparators.ts"() { + "use strict"; + init_imageUtils(); + import_pixelmatch = __toESM(require_pixelmatch()); + init_compare(); + init_webp(); + jpegjs = require("./utilsBundle").jpegjs; + colors = require("./utilsBundle").colors; + diff = require("./utilsBundle").diff; + ({ PNG } = require("./utilsBundle")); + JPEG_JS_MAX_BUFFER_SIZE_IN_MB = 5 * 1024; + } +}); + +// packages/utils/crypto.ts +function createGuid() { + return import_crypto.default.randomBytes(16).toString("hex"); +} +function calculateSha1(buffer) { + const hash = import_crypto.default.createHash("sha1"); + hash.update(buffer); + return hash.digest("hex"); +} +function encodeBase128(value2) { + const bytes = []; + do { + let byte = value2 & 127; + value2 >>>= 7; + if (bytes.length > 0) + byte |= 128; + bytes.push(byte); + } while (value2 > 0); + return Buffer.from(bytes.reverse()); +} +function generateSelfSignedCertificate() { + const { privateKey, publicKey } = import_crypto.default.generateKeyPairSync("rsa", { modulusLength: 2048 }); + const publicKeyDer = publicKey.export({ type: "pkcs1", format: "der" }); + const oneYearInMilliseconds = 365 * 24 * 60 * 60 * 1e3; + const notBefore = new Date((/* @__PURE__ */ new Date()).getTime() - oneYearInMilliseconds); + const notAfter = new Date((/* @__PURE__ */ new Date()).getTime() + oneYearInMilliseconds); + const tbsCertificate = DER.encodeSequence([ + DER.encodeExplicitContextDependent(0, DER.encodeInteger(1)), + // version + DER.encodeInteger(1), + // serialNumber + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"), + // sha256WithRSAEncryption PKCS #1 + DER.encodeNull() + ]), + // signature + DER.encodeSequence([ + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.3"), + // commonName X.520 DN component + DER.encodePrintableString("localhost") + ]) + ]), + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.10"), + // organizationName X.520 DN component + DER.encodePrintableString("Playwright Client Certificate Support") + ]) + ]) + ]), + // issuer + DER.encodeSequence([ + DER.encodeDate(notBefore), + // notBefore + DER.encodeDate(notAfter) + // notAfter + ]), + // validity + DER.encodeSequence([ + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.3"), + // commonName X.520 DN component + DER.encodePrintableString("localhost") + ]) + ]), + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.10"), + // organizationName X.520 DN component + DER.encodePrintableString("Playwright Client Certificate Support") + ]) + ]) + ]), + // subject + DER.encodeSequence([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.1"), + // rsaEncryption PKCS #1 + DER.encodeNull() + ]), + DER.encodeBitString(publicKeyDer) + ]) + // SubjectPublicKeyInfo + ]); + const signature = import_crypto.default.sign("sha256", tbsCertificate, privateKey); + const certificate = DER.encodeSequence([ + tbsCertificate, + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"), + // sha256WithRSAEncryption PKCS #1 + DER.encodeNull() + ]), + DER.encodeBitString(signature) + ]); + const certPem = [ + "-----BEGIN CERTIFICATE-----", + // Split the base64 string into lines of 64 characters + certificate.toString("base64").match(/.{1,64}/g).join("\n"), + "-----END CERTIFICATE-----" + ].join("\n"); + return { + cert: certPem, + key: privateKey.export({ type: "pkcs1", format: "pem" }) + }; +} +var import_crypto, DER; +var init_crypto = __esm({ + "packages/utils/crypto.ts"() { + "use strict"; + import_crypto = __toESM(require("crypto")); + init_assert(); + DER = class { + static encodeSequence(data) { + return this._encode(48, Buffer.concat(data)); + } + static encodeInteger(data) { + if (typeof data === "number") { + assert(data >= -128 && data <= 127); + return this._encode(2, Buffer.from([data])); + } + let start3 = 0; + while (start3 < data.length - 1 && data[start3] === 0) + start3++; + const magnitude = data.subarray(start3); + const content = magnitude[0] & 128 ? Buffer.concat([Buffer.from([0]), magnitude]) : magnitude; + return this._encode(2, content); + } + static encodeBoolean(value2) { + return this._encode(1, Buffer.from([value2 ? 255 : 0])); + } + static encodeOctetString(data) { + return this._encode(4, data); + } + static encodeObjectIdentifier(oid) { + const parts = oid.split(".").map((v) => Number(v)); + const output = [encodeBase128(40 * parts[0] + parts[1])]; + for (let i = 2; i < parts.length; i++) + output.push(encodeBase128(parts[i])); + return this._encode(6, Buffer.concat(output)); + } + static encodeNull() { + return Buffer.from([5, 0]); + } + static encodeSet(data) { + assert(data.length === 1, "Only one item in the set is supported. We'd need to sort the data to support more."); + return this._encode(49, Buffer.concat(data)); + } + static encodeExplicitContextDependent(tag, data) { + return this._encode(160 + tag, data); + } + // Primitive form, for choices such as GeneralName's dNSName [2] and iPAddress [7]. + static encodeImplicitContextDependent(tag, data) { + return this._encode(128 + tag, data); + } + static encodePrintableString(data) { + return this._encode(19, Buffer.from(data)); + } + static encodeIA5String(data) { + return this._encode(22, Buffer.from(data, "ascii")); + } + static encodeUTF8String(data) { + return this._encode(12, Buffer.from(data, "utf8")); + } + static encodeBitString(data) { + const unusedBits = 0; + const content = Buffer.concat([Buffer.from([unusedBits]), data]); + return this._encode(3, content); + } + static encodeDate(date) { + const year = date.getUTCFullYear(); + const isGeneralizedTime = year >= 2050; + const parts = [ + isGeneralizedTime ? year.toString() : year.toString().slice(-2), + (date.getUTCMonth() + 1).toString().padStart(2, "0"), + date.getUTCDate().toString().padStart(2, "0"), + date.getUTCHours().toString().padStart(2, "0"), + date.getUTCMinutes().toString().padStart(2, "0"), + date.getUTCSeconds().toString().padStart(2, "0") + ]; + const encodedDate = parts.join("") + "Z"; + const tag = isGeneralizedTime ? 24 : 23; + return this._encode(tag, Buffer.from(encodedDate)); + } + static _encode(tag, data) { + const lengthBytes = this._encodeLength(data.length); + return Buffer.concat([Buffer.from([tag]), lengthBytes, data]); + } + static _encodeLength(length) { + if (length < 128) { + return Buffer.from([length]); + } else { + const lengthBytes = []; + while (length > 0) { + lengthBytes.unshift(length & 255); + length >>= 8; + } + return Buffer.from([128 | lengthBytes.length, ...lengthBytes]); + } + } + }; + } +}); + +// packages/utils/env.ts +function getFromENV(name) { + let value2 = process.env[name]; + value2 = value2 === void 0 ? process.env[`npm_config_${name.toLowerCase()}`] : value2; + value2 = value2 === void 0 ? process.env[`npm_package_config_${name.toLowerCase()}`] : value2; + return value2; +} +function getAsBooleanFromENV(name, defaultValue) { + const value2 = getFromENV(name); + if (value2 === "false" || value2 === "0") + return false; + if (value2) + return true; + return !!defaultValue; +} +function getPackageManager() { + const env = process.env.npm_config_user_agent || ""; + if (env.includes("yarn")) + return "yarn"; + if (env.includes("pnpm")) + return "pnpm"; + return "npm"; +} +function getPackageManagerExecCommand() { + const packageManager = getPackageManager(); + if (packageManager === "yarn") + return "yarn"; + if (packageManager === "pnpm") + return "pnpm exec"; + return "npx"; +} +function isLikelyNpxGlobal() { + return process.argv.length >= 2 && process.argv[1].includes("_npx"); +} +function setPlaywrightTestProcessEnv() { + return process.env["PLAYWRIGHT_TEST"] = "1"; +} +function guessClientName() { + if (process.env.CLAUDECODE) + return "Claude Code"; + if (process.env.COPILOT_CLI) + return "GitHub Copilot"; + return "playwright-cli"; +} +function isCodingAgent() { + return !!process.env.CLAUDECODE || !!process.env.COPILOT_CLI; +} +var init_env = __esm({ + "packages/utils/env.ts"() { + "use strict"; + } +}); + +// packages/utils/debug.ts +function debugMode() { + if (_debugMode === "console") + return "console"; + if (_debugMode === "0" || _debugMode === "false") + return ""; + return _debugMode ? "inspector" : ""; +} +function isUnderTest() { + return _isUnderTest; +} +var _debugMode, _isUnderTest; +var init_debug = __esm({ + "packages/utils/debug.ts"() { + "use strict"; + init_env(); + _debugMode = getFromENV("PWDEBUG") || ""; + _isUnderTest = getAsBooleanFromENV("PWTEST_UNDER_TEST"); + } +}); + +// packages/utils/debugLogger.ts +var import_fs2, debug, debugLoggerColorMap, DebugLogger, debugLogger, kLogCount, RecentLogsCollector; +var init_debugLogger = __esm({ + "packages/utils/debugLogger.ts"() { + "use strict"; + import_fs2 = __toESM(require("fs")); + debug = require("./utilsBundle").debug; + debugLoggerColorMap = { + "api": 45, + // cyan + "protocol": 34, + // green + "install": 34, + // green + "download": 34, + // green + "browser": 0, + // reset + "socks": 92, + // purple + "client-certificates": 92, + // purple + "error": 160, + // red, + "channel": 33, + // blue + "server": 45, + // cyan + "server:channel": 34, + // green + "server:metadata": 33, + // blue, + "recorder": 45 + // cyan + }; + DebugLogger = class { + constructor() { + this._debuggers = /* @__PURE__ */ new Map(); + if (process.env.DEBUG_FILE) { + const ansiRegex2 = new RegExp([ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))" + ].join("|"), "g"); + const stream4 = import_fs2.default.createWriteStream(process.env.DEBUG_FILE); + debug.log = (data) => { + stream4.write(data.replace(ansiRegex2, "")); + stream4.write("\n"); + }; + } + } + log(name, message) { + let cachedDebugger = this._debuggers.get(name); + if (!cachedDebugger) { + cachedDebugger = debug(`pw:${name}`); + this._debuggers.set(name, cachedDebugger); + cachedDebugger.color = debugLoggerColorMap[name] || 0; + } + cachedDebugger(message); + } + isEnabled(name) { + return debug.enabled(`pw:${name}`); + } + }; + debugLogger = new DebugLogger(); + kLogCount = 150; + RecentLogsCollector = class { + constructor() { + this._logs = []; + this._listeners = []; + } + log(message) { + this._logs.push(message); + if (this._logs.length === kLogCount * 2) + this._logs.splice(0, kLogCount); + for (const listener of this._listeners) + listener(message); + } + recentLogs() { + if (this._logs.length > kLogCount) + return this._logs.slice(-kLogCount); + return this._logs; + } + onMessage(listener) { + for (const message of this._logs) + listener(message); + this._listeners.push(listener); + } + }; + } +}); + +// packages/utils/eventsHelper.ts +var EventsHelper, eventsHelper; +var init_eventsHelper = __esm({ + "packages/utils/eventsHelper.ts"() { + "use strict"; + EventsHelper = class { + static addEventListener(emitter, eventName, handler) { + emitter.on(eventName, handler); + return { emitter, eventName, handler, dispose: async () => { + emitter.removeListener(eventName, handler); + } }; + } + static removeEventListeners(listeners) { + for (const listener of listeners) + listener.emitter.removeListener(listener.eventName, listener.handler); + listeners.splice(0, listeners.length); + } + }; + eventsHelper = EventsHelper; + } +}); + +// packages/utils/fileUtils.ts +async function mkdirIfNeeded(filePath) { + await import_fs3.default.promises.mkdir(import_path3.default.dirname(filePath), { recursive: true }).catch(() => { + }); +} +async function removeFolders(dirs) { + return await Promise.all(dirs.map( + (dir) => import_fs3.default.promises.rm(dir, { recursive: true, force: true, maxRetries: 10 }).catch((e) => e) + )); +} +function canAccessFile(file) { + if (!file) + return false; + try { + import_fs3.default.accessSync(file); + return true; + } catch (e) { + return false; + } +} +function isWritable(file) { + try { + import_fs3.default.accessSync(file, import_fs3.default.constants.W_OK); + return true; + } catch { + return false; + } +} +function isSystemDirectory(dir) { + const resolved = import_path3.default.resolve(dir); + if (process.platform === "win32") { + const systemRoot = import_path3.default.resolve(process.env.SystemRoot || "C:\\Windows"); + return isPathInside(systemRoot.toLowerCase(), resolved.toLowerCase()); + } + return resolved === "/"; +} +async function copyFileAndMakeWritable(from, to) { + await import_fs3.default.promises.copyFile(from, to); + await import_fs3.default.promises.chmod(to, 436); +} +function addSuffixToFilePath(filePath, suffix) { + const ext = import_path3.default.extname(filePath); + const base = filePath.substring(0, filePath.length - ext.length); + return base + suffix + ext; +} +function sanitizeForFilePath(s) { + return s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-"); +} +function trimLongString(s, length = 100) { + if (s.length <= length) + return s; + const hash = calculateSha1(s); + const middle = `-${hash.substring(0, 5)}-`; + const start3 = Math.floor((length - middle.length) / 2); + const end = length - middle.length - start3; + return s.substring(0, start3) + middle + s.slice(-end); +} +function isPathInside(root, candidate) { + const resolvedRoot = import_path3.default.resolve(root); + const resolvedCandidate = import_path3.default.resolve(candidate); + if (resolvedCandidate === resolvedRoot) + return true; + return resolvedCandidate.startsWith(resolvedRoot + import_path3.default.sep); +} +async function resolveSymlinks(filePath) { + const resolved = import_path3.default.resolve(filePath); + try { + return await import_fs3.default.promises.realpath(resolved); + } catch (e) { + const parent = import_path3.default.dirname(resolved); + if (e.code !== "ENOENT" || parent === resolved) + throw e; + return import_path3.default.join(await resolveSymlinks(parent), import_path3.default.basename(resolved)); + } +} +function resolveWithinRoot(root, fileName) { + if (import_path3.default.isAbsolute(fileName)) + return null; + const resolvedFile = import_path3.default.resolve(root, fileName); + return isPathInside(root, resolvedFile) ? resolvedFile : null; +} +function throwingResolveWithinRoot(root, fileName) { + const resolved = resolveWithinRoot(root, fileName); + if (!resolved) + throw new Error(`Path '${fileName}' escapes root directory`); + return resolved; +} +function toPosixPath(aPath) { + return aPath.split(import_path3.default.sep).join(import_path3.default.posix.sep); +} +function makeSocketPath(domain, name) { + const userNameHash = calculateSha1(process.env.USERNAME || process.env.USER || "default").slice(0, 8); + if (process.platform === "win32") { + const socketsDir = process.env.PWTEST_SOCKETS_DIR; + const suffix = socketsDir ? `-${calculateSha1(socketsDir).slice(0, 8)}` : ""; + return `\\\\.\\pipe\\pw-${userNameHash}-${domain}-${name}${suffix}`; + } + const baseDir = process.env.PWTEST_SOCKETS_DIR || import_path3.default.join(import_os2.default.tmpdir(), `pw-${userNameHash}`); + const dir = import_path3.default.join(baseDir, domain); + let result2 = import_path3.default.join(dir, sanitizeForFilePath(name) + ".sock"); + if (Buffer.byteLength(result2) > UNIX_SOCKET_PATH_MAX) + result2 = import_path3.default.join(dir, calculateSha1(name).slice(0, 16) + ".sock"); + if (Buffer.byteLength(result2) > UNIX_SOCKET_PATH_MAX) + throw new Error(`Socket directory path is too long (${Buffer.byteLength(dir)} bytes); set PWTEST_SOCKETS_DIR to a shorter location.`); + import_fs3.default.mkdirSync(dir, { recursive: true }); + return result2; +} +var import_fs3, import_os2, import_path3, existsAsync, UNIX_SOCKET_PATH_MAX; +var init_fileUtils = __esm({ + "packages/utils/fileUtils.ts"() { + "use strict"; + import_fs3 = __toESM(require("fs")); + import_os2 = __toESM(require("os")); + import_path3 = __toESM(require("path")); + init_crypto(); + existsAsync = (path66) => new Promise((resolve) => import_fs3.default.stat(path66, (err) => resolve(!err))); + UNIX_SOCKET_PATH_MAX = 103; + } +}); + +// packages/utils/linuxUtils.ts +function getLinuxDistributionInfoSync() { + if (process.platform !== "linux") + return void 0; + if (!osRelease && !didFailToReadOSRelease) { + try { + const osReleaseText = import_fs4.default.readFileSync("/etc/os-release", "utf8"); + const fields = parseOSReleaseText(osReleaseText); + osRelease = { + id: fields.get("id") ?? "", + version: fields.get("version_id") ?? "" + }; + } catch (e) { + didFailToReadOSRelease = true; + } + } + return osRelease; +} +function parseOSReleaseText(osReleaseText) { + const fields = /* @__PURE__ */ new Map(); + for (const line of osReleaseText.split("\n")) { + const tokens = line.split("="); + const name = tokens.shift(); + let value2 = tokens.join("=").trim(); + if (value2.startsWith('"') && value2.endsWith('"')) + value2 = value2.substring(1, value2.length - 1); + if (!name) + continue; + fields.set(name.toLowerCase(), value2); + } + return fields; +} +var import_fs4, didFailToReadOSRelease, osRelease; +var init_linuxUtils = __esm({ + "packages/utils/linuxUtils.ts"() { + "use strict"; + import_fs4 = __toESM(require("fs")); + didFailToReadOSRelease = false; + } +}); + +// packages/utils/hostPlatform.ts +function calculatePlatform() { + if (process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE) { + return { + hostPlatform: process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE, + isOfficiallySupportedPlatform: false + }; + } + const platform = import_os3.default.platform(); + if (platform === "darwin") { + const ver = import_os3.default.release().split(".").map((a) => parseInt(a, 10)); + let macVersion = 0; + if (ver[0] < 18) { + macVersion = 10.13; + } else if (ver[0] === 18) { + macVersion = 10.14; + } else if (ver[0] === 19) { + macVersion = 10.15; + } else if (ver[0] < 25) { + macVersion = 11 + (ver[0] - 20); + } else { + const LAST_STABLE_MACOS_MAJOR_VERSION = 26; + macVersion = Math.min(ver[0] + 1, LAST_STABLE_MACOS_MAJOR_VERSION); + } + let macPlatform = "mac" + macVersion; + if (macVersion >= 11 && import_os3.default.cpus().some((cpu) => cpu.model.includes("Apple"))) { + macPlatform += "-arm64"; + } + return { hostPlatform: macPlatform, isOfficiallySupportedPlatform: macVersion >= 14 }; + } + if (platform === "linux") { + if (!["x64", "arm64"].includes(import_os3.default.arch())) + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; + const archSuffix = "-" + import_os3.default.arch(); + const distroInfo = getLinuxDistributionInfoSync(); + if (distroInfo?.id === "ubuntu" || distroInfo?.id === "pop" || distroInfo?.id === "neon" || distroInfo?.id === "tuxedo") { + const isUbuntu = distroInfo?.id === "ubuntu"; + const version3 = distroInfo?.version; + const major = parseInt(distroInfo.version, 10); + if (major < 20) + return { hostPlatform: "ubuntu18.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (major < 22) + return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (major < 24) + return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "22.04" }; + if (major < 26) + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "24.04" }; + if (major < 28) + return { hostPlatform: "ubuntu26.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "26.04" }; + return { hostPlatform: "ubuntu" + distroInfo.version + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (distroInfo?.id === "linuxmint") { + const mintMajor = parseInt(distroInfo.version, 10); + if (mintMajor <= 20) + return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (mintMajor === 21) + return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: false }; + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (distroInfo?.id === "debian" || distroInfo?.id === "raspbian") { + if (distroInfo?.version === "11") + return { hostPlatform: "debian11" + archSuffix, isOfficiallySupportedPlatform: false }; + const isOfficiallySupportedPlatform2 = distroInfo?.id === "debian"; + if (distroInfo?.version === "12") + return { hostPlatform: "debian12" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if (distroInfo?.version === "13") + return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if (distroInfo?.version === "") + return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + } + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (platform === "win32") + return { hostPlatform: "win64", isOfficiallySupportedPlatform: true }; + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; +} +function toShortPlatform(hostPlatform2) { + if (hostPlatform2 === "") + return ""; + if (hostPlatform2 === "win64") + return "win-x64"; + if (hostPlatform2.startsWith("mac")) + return hostPlatform2.endsWith("arm64") ? "mac-arm64" : "mac-x64"; + return hostPlatform2.endsWith("arm64") ? "linux-arm64" : "linux-x64"; +} +var import_os3, hostPlatform, isOfficiallySupportedPlatform, shortPlatform; +var init_hostPlatform = __esm({ + "packages/utils/hostPlatform.ts"() { + "use strict"; + import_os3 = __toESM(require("os")); + init_linuxUtils(); + ({ hostPlatform, isOfficiallySupportedPlatform } = calculatePlatform()); + shortPlatform = toShortPlatform(hostPlatform); + } +}); + +// packages/utils/stackTrace.ts +function captureRawStack() { + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 50; + const error = new Error(); + const stack = error.stack || ""; + Error.stackTraceLimit = stackTraceLimit; + return stack.split("\n"); +} +function parseStackFrame(text2) { + const match = text2 && text2.match(re); + if (!match) + return null; + let fname = match[2]; + let file = match[7]; + if (!file) + return null; + if (!showInternalStackFrames() && (file.startsWith("internal") || file.startsWith("node:"))) + return null; + const line = match[8]; + const column = match[9]; + const closeParen = match[11] === ")"; + const frame = { + file: "", + line: 0, + column: 0 + }; + if (line) + frame.line = Number(line); + if (column) + frame.column = Number(column); + if (closeParen && file) { + let closes = 0; + for (let i = file.length - 1; i > 0; i--) { + if (file.charAt(i) === ")") { + closes++; + } else if (file.charAt(i) === "(" && file.charAt(i - 1) === " ") { + closes--; + if (closes === -1 && file.charAt(i - 1) === " ") { + const before = file.slice(0, i - 1); + const after = file.slice(i + 1); + file = after; + fname += ` (${before}`; + break; + } + } + } + } + if (fname) { + const methodMatch = fname.match(methodRe); + if (methodMatch) + fname = methodMatch[1]; + } + if (file) { + if (file.startsWith("file://")) + file = fileURLToPath(file); + frame.file = file; + } + if (fname) + frame.function = fname; + return frame; +} +function rewriteErrorMessage(e, newMessage) { + const lines = (e.stack?.split("\n") || []).filter((l) => l.startsWith(" at ")); + e.message = newMessage; + const errorTitle = `${e.name}: ${e.message}`; + if (lines.length) + e.stack = `${errorTitle} +${lines.join("\n")}`; + return e; +} +function stringifyStackFrames(frames) { + const stackLines = []; + for (const frame of frames) { + if (frame.function) + stackLines.push(` at ${frame.function} (${frame.file}:${frame.line}:${frame.column})`); + else + stackLines.push(` at ${frame.file}:${frame.line}:${frame.column}`); + } + return stackLines; +} +function splitErrorMessage(message) { + const separationIdx = message.indexOf(":"); + return { + name: separationIdx !== -1 ? message.slice(0, separationIdx) : "", + message: separationIdx !== -1 && separationIdx + 2 <= message.length ? message.substring(separationIdx + 2) : message + }; +} +function parseErrorStack(stack) { + const lines = stack.split("\n"); + let firstStackLine = lines.findIndex((line) => line.startsWith(" at ")); + if (firstStackLine === -1) + firstStackLine = lines.length; + const message = lines.slice(0, firstStackLine).join("\n"); + const stackLines = lines.slice(firstStackLine); + let location2; + for (const line of stackLines) { + const frame = parseStackFrame(line); + if (!frame || !frame.file) + continue; + if (belongsToNodeModules(frame.file)) + continue; + location2 = { file: frame.file, column: frame.column || 0, line: frame.line || 0 }; + break; + } + return { message, stackLines, location: location2 }; +} +function belongsToNodeModules(file) { + return file.includes(`${import_path4.default.sep}node_modules${import_path4.default.sep}`); +} +function filterStackFile(file) { + if (_showInternalStackFrames) + return true; + if (!!_coreDir && file.startsWith(_coreDir)) + return false; + if (_boxedStackPrefixes.some((prefix) => file.startsWith(prefix))) + return false; + if (isUnderTest() && file.match(/[/\\]packages[/\\](playwright|playwright-core|utils|isomorphic|injected)[/\\]/)) + return false; + if (isUnderTest() && file.match(/[/\\]playwright[^/\\]*[/\\]node_modules[/\\]/)) + return false; + return true; +} +function filteredStackTrace(rawStack) { + const frames = []; + for (const line of rawStack) { + const frame = parseStackFrame(line); + if (!frame || !frame.file) + continue; + if (!filterStackFile(frame.file)) + continue; + frames.push(frame); + } + return frames; +} +function fileURLToPath(fileUrl) { + if (!fileUrl.startsWith("file://")) + return fileUrl; + let filePath = decodeURIComponent(fileUrl.slice(7)); + if (filePath.startsWith("/") && /^[a-zA-Z]:/.test(filePath.slice(1))) + filePath = filePath.slice(1); + return filePath.replace(/\//g, import_path4.default.sep); +} +function setCoreDir(dir) { + _coreDir = dir; +} +function coreDir() { + return _coreDir; +} +function setBoxedStackPrefixes(prefixes) { + _boxedStackPrefixes = prefixes; +} +function showInternalStackFrames() { + return _showInternalStackFrames; +} +var import_path4, re, methodRe, _coreDir, _boxedStackPrefixes, _showInternalStackFrames; +var init_stackTrace = __esm({ + "packages/utils/stackTrace.ts"() { + "use strict"; + import_path4 = __toESM(require("path")); + init_env(); + init_debug(); + re = new RegExp( + "^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$" + ); + methodRe = /^(.*?) \[as (.*?)\]$/; + _boxedStackPrefixes = []; + _showInternalStackFrames = getAsBooleanFromENV("PWDEBUGIMPL"); + } +}); + +// packages/utils/network.ts +function httpRequest(params2, onResponse, onError) { + let url3 = new URL(params2.url); + const options = { + method: params2.method || "GET", + headers: params2.headers, + ...happyEyeballsOptions + }; + if (params2.socketTimeout !== void 0) + options.timeout = params2.socketTimeout; + if (params2.rejectUnauthorized !== void 0) + options.rejectUnauthorized = params2.rejectUnauthorized; + const proxyURL = getProxyForUrl(params2.url); + if (proxyURL) { + const parsedProxyURL = normalizeProxyURL(proxyURL); + if (params2.url.startsWith("http:")) { + options.path = url3.toString(); + const headers = options.headers || {}; + if (!Object.keys(headers).some((header) => header.toLowerCase() === "host")) + headers.host = url3.host; + options.headers = headers; + url3 = parsedProxyURL; + } else { + options.agent = new HttpsProxyAgent(parsedProxyURL); + } + } + let cancelRequest; + const requestCallback = (res) => { + const statusCode = res.statusCode || 0; + if (statusCode >= 300 && statusCode < 400 && res.headers.location) { + request2.destroy(); + cancelRequest = httpRequest({ ...params2, url: new URL(res.headers.location, params2.url).toString() }, onResponse, onError).cancel; + } else { + onResponse(res); + } + }; + const request2 = url3.protocol === "https:" ? import_https.default.request(url3, options, requestCallback) : import_http.default.request(url3, options, requestCallback); + request2.on("error", (error) => onError(flattenAggregateError(error))); + if (params2.socketTimeout !== void 0) { + request2.setTimeout(params2.socketTimeout, () => { + onError(new Error(`Request to ${params2.url} timed out after ${params2.socketTimeout}ms`)); + request2.abort(); + }); + } + cancelRequest = (e) => { + try { + request2.destroy(e); + } catch { + } + }; + request2.end(params2.data); + return { cancel: (e) => cancelRequest(e) }; +} +function shouldBypassProxy(url3, bypass) { + if (!bypass) + return false; + const domains = bypass.split(",").map((s) => { + s = s.trim(); + if (!s.startsWith(".")) + s = "." + s; + return s; + }); + const domain = "." + url3.hostname; + return domains.some((d) => domain.endsWith(d)); +} +function normalizeProxyURL(proxy) { + proxy = proxy.trim(); + if (!/^\w+:\/\//.test(proxy)) + proxy = "http://" + proxy; + return new URL(proxy); +} +function proxySettingsFromString(proxy) { + try { + const url3 = normalizeProxyURL(proxy); + if (url3.username || url3.password) { + return { + server: url3.protocol + "//" + url3.host, + username: decodeURIComponent(url3.username), + password: decodeURIComponent(url3.password) + }; + } + } catch { + } + return { server: proxy }; +} +function createProxyAgent(proxy, forUrl) { + if (!proxy) + return; + if (forUrl && proxy.bypass && shouldBypassProxy(forUrl, proxy.bypass)) + return; + const proxyURL = normalizeProxyURL(proxy.server); + if (proxyURL.protocol?.startsWith("socks")) { + if (proxyURL.protocol === "socks5:") + proxyURL.protocol = "socks5h:"; + else if (proxyURL.protocol === "socks4:") + proxyURL.protocol = "socks4a:"; + return new SocksProxyAgent(proxyURL); + } + if (proxy.username) { + proxyURL.username = proxy.username; + proxyURL.password = proxy.password || ""; + } + if (forUrl && ["ws:", "wss:"].includes(forUrl.protocol)) { + return new HttpsProxyAgent(proxyURL); + } + return new HttpsProxyAgent(proxyURL); +} +function flattenAggregateError(error) { + const errors = error.errors; + if (error.name === "AggregateError" && !error.message && errors?.length) + return rewriteErrorMessage(error, errors.map((e) => e.message).join("\n")); + return error; +} +async function createSocket(host, port) { + return new Promise((resolve, reject) => { + const socket = import_net.default.createConnection({ host, port, ...happyEyeballsOptions }); + socket.on("connect", () => resolve(socket)); + socket.on("error", (error) => reject(flattenAggregateError(error))); + }); +} +function createHttpServer(...args) { + const server = import_http.default.createServer(...args); + decorateServer(server); + return server; +} +function createHttpsServer(...args) { + const server = import_https.default.createServer(...args); + decorateServer(server); + return server; +} +function createHttp2Server(...args) { + const server = import_http2.default.createSecureServer(...args); + decorateServer(server); + return server; +} +async function startHttpServer(server, options) { + const { host = "localhost", port = 0 } = options; + const errorPromise = new ManualPromise(); + const errorListener = (error) => errorPromise.reject(error); + server.on("error", errorListener); + try { + server.listen(port, host); + await Promise.race([ + new Promise((cb) => server.once("listening", cb)), + errorPromise + ]); + } finally { + server.removeListener("error", errorListener); + } +} +async function isURLAvailable(url3, ignoreHTTPSErrors, onLog, onStdErr) { + let statusCode = await httpStatusCode(url3, ignoreHTTPSErrors, onLog, onStdErr); + if (statusCode === 404 && url3.pathname === "/") { + const indexUrl = new URL(url3); + indexUrl.pathname = "/index.html"; + statusCode = await httpStatusCode(indexUrl, ignoreHTTPSErrors, onLog, onStdErr); + } + return statusCode >= 200 && statusCode < 404; +} +async function httpStatusCode(url3, ignoreHTTPSErrors, onLog, onStdErr) { + return new Promise((resolve) => { + onLog?.(`HTTP GET: ${url3}`); + httpRequest({ + url: url3.toString(), + headers: { Accept: "*/*" }, + rejectUnauthorized: !ignoreHTTPSErrors + }, (res) => { + res.resume(); + const statusCode = res.statusCode ?? 0; + onLog?.(`HTTP Status: ${statusCode}`); + resolve(statusCode); + }, (error) => { + if (error.code === "DEPTH_ZERO_SELF_SIGNED_CERT") + onStdErr?.(`[WebServer] Self-signed certificate detected. Try adding ignoreHTTPSErrors: true to config.webServer.`); + onLog?.(`Error while checking if ${url3} is available: ${error.message}`); + resolve(0); + }); + }); +} +function decorateServer(server) { + const sockets = /* @__PURE__ */ new Set(); + server.on("connection", (socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + }); + const close3 = server.close; + server.close = (callback) => { + for (const socket of sockets) + socket.destroy(); + sockets.clear(); + return close3.call(server, callback); + }; +} +var import_dns, import_http, import_http2, import_https, import_net, HttpsProxyAgent, SocksProxyAgent, getProxyForUrl, NET_DEFAULT_TIMEOUT, dualStackLookup, happyEyeballsOptions; +var init_network = __esm({ + "packages/utils/network.ts"() { + "use strict"; + import_dns = __toESM(require("dns")); + import_http = __toESM(require("http")); + import_http2 = __toESM(require("http2")); + import_https = __toESM(require("https")); + import_net = __toESM(require("net")); + init_manualPromise(); + init_stackTrace(); + ({ HttpsProxyAgent } = require("./utilsBundle")); + ({ SocksProxyAgent } = require("./utilsBundle")); + ({ getProxyForUrl } = require("./utilsBundle")); + NET_DEFAULT_TIMEOUT = 3e4; + dualStackLookup = (hostname, options, callback) => { + const defaultFamilies = import_dns.default.getDefaultResultOrder() === "ipv4first" ? [4, 6] : [6, 4]; + const families = options.family === 4 || options.family === 6 ? [options.family] : defaultFamilies; + void Promise.allSettled(families.map((family) => import_dns.default.promises.lookup(hostname, { all: true, family }))).then((results) => { + const perFamily = results.map((result2) => result2.status === "fulfilled" ? result2.value : []); + const addresses = []; + for (let i = 0; i < Math.max(...perFamily.map((list) => list.length)); i++) { + for (const list of perFamily) { + if (list[i]) + addresses.push(list[i]); + } + } + if (!addresses.length) { + const firstError = results.map((result2) => result2.status === "rejected" ? result2.reason : void 0).find(Boolean); + callback(firstError ?? new Error(`Cannot resolve address for ${hostname}`), ""); + return; + } + if (options.all) + callback(null, addresses); + else + callback(null, addresses[0].address, addresses[0].family); + }); + }; + happyEyeballsOptions = { + lookup: dualStackLookup, + autoSelectFamily: true, + autoSelectFamilyAttemptTimeout: Math.max(5e3, import_net.default.getDefaultAutoSelectFamilyAttemptTimeout()) + }; + } +}); + +// packages/utils/httpServer.ts +function computeAllowedHosts(requested, bound) { + const loopback = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "localhost"]); + const isLoopback = (h) => h !== void 0 && loopback.has(h.toLowerCase()); + if (!isLoopback(requested) && requested !== void 0) + return null; + if (!isLoopback(bound) && requested === void 0) + return null; + return /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]); +} +function isAllowedHost(request2, allowedHosts) { + if (!allowedHosts) + return true; + const host = request2.headers.host?.toLowerCase(); + const hostname = host ? hostnameFromHostHeader(host) : void 0; + return !!hostname && allowedHosts.has(hostname); +} +function urlHostFromAddress(address) { + return address.family === "IPv6" ? `[${address.address}]` : address.address; +} +function hostnameFromHostHeader(host) { + if (host.startsWith("[")) { + const end = host.indexOf("]"); + return end < 0 ? host : host.substring(0, end + 1); + } + const colon = host.indexOf(":"); + return colon < 0 ? host : host.substring(0, colon); +} +function serveFolder(folder) { + const server = new HttpServer(folder); + server.routePrefix("/", (request2, response2) => { + let relativePath = new URL("http://localhost" + request2.url).pathname; + if (relativePath.startsWith("/trace/file")) { + const url3 = new URL("http://localhost" + request2.url); + const requested = url3.searchParams.get("path"); + if (!requested) + return false; + const resolved = import_path5.default.resolve(requested); + try { + return server.serveFile(request2, response2, resolved); + } catch (e) { + return false; + } + } + if (relativePath === "/") + relativePath = "/index.html"; + const absolutePath = import_path5.default.join(folder, ...relativePath.split("/")); + return server.serveFile(request2, response2, absolutePath); + }); + return server; +} +var import_fs5, import_path5, mime, wsServer, HttpServer; +var init_httpServer = __esm({ + "packages/utils/httpServer.ts"() { + "use strict"; + import_fs5 = __toESM(require("fs")); + import_path5 = __toESM(require("path")); + init_assert(); + init_crypto(); + init_fileUtils(); + init_network(); + mime = require("./utilsBundle").mime; + ({ wsServer } = require("./utilsBundle")); + HttpServer = class { + constructor(staticRoot) { + this._urlPrefixPrecise = ""; + this._urlPrefixHumanReadable = ""; + this._port = 0; + this._started = false; + this._routes = []; + // Allowed Host headers; null disables the check (host bound to a public address). + this._allowedHosts = null; + this._server = createHttpServer(this._onRequest.bind(this)); + this._staticRoot = staticRoot ? import_path5.default.resolve(staticRoot) : void 0; + } + server() { + return this._server; + } + routePrefix(prefix, handler) { + this._routes.push({ prefix, handler }); + } + routePath(path66, handler) { + this._routes.push({ exact: path66, handler }); + } + port() { + return this._port; + } + createWebSocket(transportFactory, guid) { + assert(!this._wsGuid, "can only create one main websocket transport per server"); + this._wsGuid = guid || createGuid(); + const wsPath = "/" + this._wsGuid; + const wss = new wsServer({ noServer: true }); + this._server.on("upgrade", (request2, socket, head) => { + const pathname = new URL(request2.url ?? "/", "http://localhost").pathname; + if (pathname !== wsPath) + return; + if (!isAllowedHost(request2, this._allowedHosts)) { + socket.write(`HTTP/${request2.httpVersion} 403 Forbidden\r +\r +`); + socket.destroy(); + return; + } + wss.handleUpgrade(request2, socket, head, (ws4) => wss.emit("connection", ws4, request2)); + }); + wss.on("connection", (ws4, request2) => { + const url3 = new URL(request2.url ?? "/", "http://localhost"); + const transport = transportFactory(url3); + transport.sendEvent = (method2, params2) => ws4.send(JSON.stringify({ method: method2, params: params2 })); + transport.close = () => ws4.close(); + transport.onconnect(); + ws4.on("message", async (message) => { + const { id, method: method2, params: params2 } = JSON.parse(String(message)); + try { + const result2 = await transport.dispatch(method2, params2); + ws4.send(JSON.stringify({ id, result: result2 })); + } catch (e) { + ws4.send(JSON.stringify({ id, error: String(e) })); + } + }); + ws4.on("close", () => transport.onclose()); + ws4.on("error", () => transport.onclose()); + }); + } + wsGuid() { + return this._wsGuid; + } + async createViteDevServer(options) { + const loadVite = new Function('return import("vite")'); + const vite = await loadVite(); + return await vite.createServer({ + root: options.root, + base: options.base, + server: { + middlewareMode: true, + // Dedicated path so Vite's HMR websocket does not collide with any + // websocket HttpServer owns via createWebSocket(). + hmr: { path: "/__vite_hmr", server: this._server } + }, + appType: "spa", + clearScreen: false + }); + } + // HMR end + // Vite's middleware `next` callback for the "no middleware matched" case; + // emits a 404 only if nothing downstream already responded. + static notFoundFallback(response2) { + return () => { + if (!response2.headersSent) { + response2.statusCode = 404; + response2.end(); + } + }; + } + async start(options = {}) { + assert(!this._started, "server already started"); + this._started = true; + const host = options.host; + if (options.preferredPort) { + try { + await startHttpServer(this._server, { port: options.preferredPort, host }); + } catch (e) { + if (!e || !e.message || !e.message.includes("EADDRINUSE")) + throw e; + await startHttpServer(this._server, { host }); + } + } else { + await startHttpServer(this._server, { port: options.port, host }); + } + const address = this._server.address(); + assert(address, "Could not bind server socket"); + if (typeof address === "string") { + this._urlPrefixPrecise = address; + this._urlPrefixHumanReadable = address; + } else { + this._port = address.port; + this._urlPrefixPrecise = `http://${urlHostFromAddress(address)}:${address.port}`; + this._urlPrefixHumanReadable = `http://${host ?? "localhost"}:${address.port}`; + this._allowedHosts = computeAllowedHosts(host, address.address); + } + } + async stop() { + await new Promise((cb) => this._server.close(cb)); + } + urlPrefix(purpose) { + return purpose === "human-readable" ? this._urlPrefixHumanReadable : this._urlPrefixPrecise; + } + serveFile(request2, response2, absoluteFilePath, headers, options) { + if (this._staticRoot && !options?.skipRootCheck && !isPathInside(this._staticRoot, absoluteFilePath)) { + response2.statusCode = 403; + response2.end(); + return true; + } + try { + for (const [name, value2] of Object.entries(headers || {})) + response2.setHeader(name, value2); + if (request2.headers.range) + this._serveRangeFile(request2, response2, absoluteFilePath); + else + this._serveFile(response2, absoluteFilePath); + return true; + } catch (e) { + return false; + } + } + _serveFile(response2, absoluteFilePath) { + const content = import_fs5.default.readFileSync(absoluteFilePath); + response2.statusCode = 200; + const contentType = mime.getType(import_path5.default.extname(absoluteFilePath)) || "application/octet-stream"; + response2.setHeader("Content-Type", contentType); + response2.setHeader("Content-Length", content.byteLength); + response2.end(content); + } + _serveRangeFile(request2, response2, absoluteFilePath) { + const range = request2.headers.range; + if (!range || !range.startsWith("bytes=") || range.includes(", ") || [...range].filter((char) => char === "-").length !== 1) { + response2.statusCode = 400; + return response2.end("Bad request"); + } + const [startStr, endStr] = range.replace(/bytes=/, "").split("-"); + let start3; + let end; + const size = import_fs5.default.statSync(absoluteFilePath).size; + if (startStr !== "" && endStr === "") { + start3 = +startStr; + end = size - 1; + } else if (startStr === "" && endStr !== "") { + start3 = size - +endStr; + end = size - 1; + } else { + start3 = +startStr; + end = +endStr; + } + if (Number.isNaN(start3) || Number.isNaN(end) || start3 >= size || end >= size || start3 > end) { + response2.writeHead(416, { + "Content-Range": `bytes */${size}` + }); + return response2.end(); + } + response2.writeHead(206, { + "Content-Range": `bytes ${start3}-${end}/${size}`, + "Accept-Ranges": "bytes", + "Content-Length": end - start3 + 1, + "Content-Type": mime.getType(import_path5.default.extname(absoluteFilePath)) + }); + const readable = import_fs5.default.createReadStream(absoluteFilePath, { start: start3, end }); + readable.pipe(response2); + } + _onRequest(request2, response2) { + if (request2.method === "OPTIONS") { + response2.writeHead(200); + response2.end(); + return; + } + if (!isAllowedHost(request2, this._allowedHosts)) { + response2.statusCode = 403; + response2.end(); + return; + } + request2.on("error", () => response2.end()); + try { + if (!request2.url) { + response2.end(); + return; + } + const url3 = new URL("http://localhost" + request2.url); + for (const route2 of this._routes) { + if (route2.exact && url3.pathname === route2.exact && route2.handler(request2, response2)) + return; + if (route2.prefix && url3.pathname.startsWith(route2.prefix) && route2.handler(request2, response2)) + return; + } + response2.statusCode = 404; + response2.end(); + } catch (e) { + response2.end(); + } + } + }; + } +}); + +// packages/utils/processLauncher.ts +async function gracefullyCloseAll() { + await Promise.all(Array.from(gracefullyCloseSet).map((gracefullyClose) => gracefullyClose().catch((e) => { + }))); +} +function gracefullyProcessExitDoNotHang(code, onExit2) { + const beforeExit = onExit2 ? () => onExit2().catch(() => { + }) : () => Promise.resolve(); + const callback = () => beforeExit().then(() => (0, import_bootstrap.processExit)(code)); + setTimeout(callback, 3e4); + gracefullyCloseAll().then(callback); +} +function exitHandler() { + for (const kill of killSet) + kill(); +} +function sigintHandler() { + const exitWithCode130 = () => { + if (isUnderTest()) { + setTimeout(() => (0, import_bootstrap.processExit)(130), 1e3); + } else { + (0, import_bootstrap.processExit)(130); + } + }; + if (sigintHandlerCalled) { + process.off("SIGINT", sigintHandler); + for (const kill of killSet) + kill(); + exitWithCode130(); + } else { + sigintHandlerCalled = true; + gracefullyCloseAll().then(() => exitWithCode130()); + } +} +function sigtermHandler() { + gracefullyCloseAll(); +} +function sighupHandler() { + gracefullyCloseAll(); +} +function addProcessHandlerIfNeeded(name) { + if (!installedHandlers.has(name)) { + installedHandlers.add(name); + process.on(name, processHandlers[name]); + } +} +function removeProcessHandlersIfNeeded() { + if (killSet.size) + return; + for (const handler of installedHandlers) + process.off(handler, processHandlers[handler]); + installedHandlers.clear(); +} +async function launchProcess(options) { + const stdio = options.stdio === "pipe" ? ["ignore", "pipe", "pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe"]; + options.log(` ${options.command} ${options.args ? options.args.join(" ") : ""}`); + const spawnOptions = { + // On non-windows platforms, `detached: true` makes child process a leader of a new + // process group, making it possible to kill child process tree with `.kill(-pid)` command. + // @see https://nodejs.org/api/child_process.html#child_process_options_detached + detached: process.platform !== "win32", + env: options.env, + cwd: options.cwd, + shell: options.shell, + stdio + }; + const spawnedProcess = childProcess.spawn(options.command, options.args || [], spawnOptions); + const cleanup = async () => { + options.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`); + const errors = await removeFolders(options.tempDirectories); + for (let i = 0; i < options.tempDirectories.length; ++i) { + if (errors[i]) + options.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${options.tempDirectories[i]}: ${errors[i]}`); + } + options.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`); + }; + spawnedProcess.on("error", () => { + }); + if (!spawnedProcess.pid) { + let failed; + const failedPromise = new Promise((f, r) => failed = f); + spawnedProcess.once("error", (error) => { + failed(new Error("Failed to launch: " + error)); + }); + return failedPromise.then(async (error) => { + await cleanup(); + throw error; + }); + } + options.log(` pid=${spawnedProcess.pid}`); + const stdout = readline.createInterface({ input: spawnedProcess.stdout }); + stdout.on("line", (data) => { + options.log(`[pid=${spawnedProcess.pid}][out] ` + data); + }); + const stderr = readline.createInterface({ input: spawnedProcess.stderr }); + stderr.on("line", (data) => { + options.log(`[pid=${spawnedProcess.pid}][err] ` + data); + }); + let processClosed = false; + let fulfillCleanup = () => { + }; + const waitForCleanup = new Promise((f) => fulfillCleanup = f); + spawnedProcess.once("close", (exitCode, signal) => { + options.log(`[pid=${spawnedProcess.pid}] `); + processClosed = true; + gracefullyCloseSet.delete(gracefullyClose); + killSet.delete(killProcessAndCleanup); + removeProcessHandlersIfNeeded(); + options.onExit(exitCode, signal); + cleanup().then(fulfillCleanup); + }); + addProcessHandlerIfNeeded("exit"); + if (options.handleSIGINT) + addProcessHandlerIfNeeded("SIGINT"); + if (options.handleSIGTERM) + addProcessHandlerIfNeeded("SIGTERM"); + if (options.handleSIGHUP) + addProcessHandlerIfNeeded("SIGHUP"); + gracefullyCloseSet.add(gracefullyClose); + killSet.add(killProcessAndCleanup); + let gracefullyClosing = false; + async function gracefullyClose() { + if (gracefullyClosing) { + options.log(`[pid=${spawnedProcess.pid}] `); + killProcess(); + await waitForCleanup; + return; + } + gracefullyClosing = true; + options.log(`[pid=${spawnedProcess.pid}] `); + await options.attemptToGracefullyClose().catch(() => killProcess()); + await waitForCleanup; + options.log(`[pid=${spawnedProcess.pid}] `); + } + function killProcess() { + gracefullyCloseSet.delete(gracefullyClose); + killSet.delete(killProcessAndCleanup); + removeProcessHandlersIfNeeded(); + options.log(`[pid=${spawnedProcess.pid}] `); + if (spawnedProcess.pid && !spawnedProcess.killed && !processClosed) { + options.log(`[pid=${spawnedProcess.pid}] `); + try { + if (process.platform === "win32") + killProcessTree(spawnedProcess.pid); + else + process.kill(-spawnedProcess.pid, "SIGKILL"); + } catch (e) { + options.log(`[pid=${spawnedProcess.pid}] exception while trying to kill process: ${e}`); + } + } else { + options.log(`[pid=${spawnedProcess.pid}] `); + } + } + function killProcessAndCleanup() { + killProcess(); + options.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`); + for (const dir of options.tempDirectories) { + try { + import_fs6.default.rmSync(dir, { force: true, recursive: true, maxRetries: 5 }); + } catch (e) { + options.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${dir}: ${e}`); + } + } + options.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`); + } + function killAndWait() { + killProcess(); + return waitForCleanup; + } + return { launchedProcess: spawnedProcess, gracefullyClose, kill: killAndWait }; +} +function killProcessTree(pid) { + try { + if (process.platform === "win32") + childProcess.spawnSync(`taskkill /pid ${pid} /T /F`, { shell: true, windowsHide: true }); + else + process.kill(pid, "SIGKILL"); + } catch { + } +} +function spawnAsync(cmd, args, options = {}) { + const { timeout, ...spawnOptions } = options; + const child = childProcess.spawn(cmd, args, { windowsHide: true, ...spawnOptions }); + return new Promise((resolve) => { + let stdout = ""; + let stderr = ""; + if (child.stdout) + child.stdout.on("data", (data) => stdout += data.toString()); + if (child.stderr) + child.stderr.on("data", (data) => stderr += data.toString()); + const timer = timeout ? setTimeout(() => { + if (child.pid) + killProcessTree(child.pid); + resolve({ stdout, stderr, code: null, timedOut: true }); + }, timeout) : void 0; + child.on("close", (code) => { + clearTimeout(timer); + resolve({ stdout, stderr, code }); + }); + child.on("error", (error) => { + clearTimeout(timer); + resolve({ stdout, stderr, code: 0, error }); + }); + }); +} +function envArrayToObject(env) { + const result2 = {}; + for (const { name, value: value2 } of env) + result2[name] = value2; + return result2; +} +var childProcess, import_fs6, readline, import_bootstrap, gracefullyCloseSet, killSet, sigintHandlerCalled, installedHandlers, processHandlers; +var init_processLauncher = __esm({ + "packages/utils/processLauncher.ts"() { + "use strict"; + childProcess = __toESM(require("child_process")); + import_fs6 = __toESM(require("fs")); + readline = __toESM(require("readline")); + init_fileUtils(); + init_debug(); + import_bootstrap = require("./bootstrap"); + gracefullyCloseSet = /* @__PURE__ */ new Set(); + killSet = /* @__PURE__ */ new Set(); + sigintHandlerCalled = false; + installedHandlers = /* @__PURE__ */ new Set(); + processHandlers = { + exit: exitHandler, + SIGINT: sigintHandler, + SIGTERM: sigtermHandler, + SIGHUP: sighupHandler + }; + } +}); + +// packages/utils/serializedFS.ts +var import_fs7, yazl, APPEND_CHUNK_SIZE, SerializedFS; +var init_serializedFS = __esm({ + "packages/utils/serializedFS.ts"() { + "use strict"; + import_fs7 = __toESM(require("fs")); + init_manualPromise(); + yazl = require("./utilsBundle").yazl; + APPEND_CHUNK_SIZE = 64 * 1024; + SerializedFS = class { + constructor() { + this._buffers = /* @__PURE__ */ new Map(); + this._operations = []; + this._operationsDone = new ManualPromise(); + this._operationsDone.resolve(); + } + mkdir(dir) { + this._appendOperation({ op: "mkdir", dir }); + } + writeFile(file, content, skipIfExists) { + this._buffers.delete(file); + this._appendOperation({ op: "writeFile", file, content, skipIfExists }); + } + appendFile(file, text2, flush) { + if (!this._buffers.has(file)) + this._buffers.set(file, []); + const buffer = this._buffers.get(file); + buffer.push(text2); + let size = 0; + for (const chunk of buffer) + size += chunk.length; + if (flush || size >= APPEND_CHUNK_SIZE) + this._flushFile(file); + } + _flushFile(file) { + const buffer = this._buffers.get(file); + if (buffer === void 0) + return; + const content = buffer.join(""); + this._buffers.delete(file); + this._appendOperation({ op: "appendFile", file, content }); + } + copyFile(from, to) { + this._flushFile(from); + this._buffers.delete(to); + this._appendOperation({ op: "copyFile", from, to }); + } + async sync() { + for (const file of this._buffers.keys()) + this._flushFile(file); + await this._operationsDone; + if (this._error) { + const e = this._error; + this._error = void 0; + throw e; + } + } + zip(entries, zipFileName) { + for (const file of this._buffers.keys()) + this._flushFile(file); + this._appendOperation({ op: "zip", entries, zipFileName }); + } + // This method serializes all writes to the trace. + _appendOperation(op) { + const last = this._operations[this._operations.length - 1]; + if (last?.op === "appendFile" && op.op === "appendFile" && last.file === op.file && last.content.length < APPEND_CHUNK_SIZE) { + last.content += op.content; + return; + } + this._operations.push(op); + if (this._operationsDone.isDone()) + this._performOperations(); + } + async _performOperations() { + this._operationsDone = new ManualPromise(); + while (this._operations.length) { + const op = this._operations.shift(); + if (this._error) + continue; + try { + await this._performOperation(op); + } catch (e) { + this._error = e; + } + } + this._operationsDone.resolve(); + } + async _performOperation(op) { + switch (op.op) { + case "mkdir": { + await import_fs7.default.promises.mkdir(op.dir, { recursive: true }); + return; + } + case "writeFile": { + if (op.skipIfExists) + await import_fs7.default.promises.writeFile(op.file, op.content, { flag: "wx" }).catch(() => { + }); + else + await import_fs7.default.promises.writeFile(op.file, op.content); + return; + } + case "copyFile": { + await import_fs7.default.promises.copyFile(op.from, op.to); + return; + } + case "appendFile": { + await import_fs7.default.promises.appendFile(op.file, op.content); + return; + } + case "zip": { + const zipFile = new yazl.ZipFile(); + const result2 = new ManualPromise(); + zipFile.on("error", (error) => result2.reject(error)); + for (const entry of op.entries) + zipFile.addFile(entry.value, entry.name); + zipFile.end(); + zipFile.outputStream.pipe(import_fs7.default.createWriteStream(op.zipFileName)).on("close", () => result2.resolve()).on("error", (error) => result2.reject(error)); + await result2; + return; + } + } + } + }; + } +}); + +// packages/utils/socksProxy.ts +function hexToNumber(hex) { + return [...hex].reduce((value2, digit2) => { + const code = digit2.charCodeAt(0); + if (code >= 48 && code <= 57) + return value2 + code; + if (code >= 97 && code <= 102) + return value2 + (code - 97) + 10; + if (code >= 65 && code <= 70) + return value2 + (code - 65) + 10; + throw new Error("Invalid IPv6 token " + hex); + }, 0); +} +function ipToSocksAddress(address) { + const ipv4Mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); + if (ipv4Mapped) + address = ipv4Mapped[1]; + if (import_net2.default.isIPv4(address)) { + return [ + 1, + // IPv4 + ...address.split(".", 4).map((t) => +t & 255) + // Address + ]; + } + if (import_net2.default.isIPv6(address)) { + const result2 = [4]; + const tokens = address.split(":", 8); + while (tokens.length < 8) + tokens.unshift(""); + for (const token of tokens) { + const value2 = hexToNumber(token); + result2.push(value2 >> 8 & 255, value2 & 255); + } + return result2; + } + throw new Error("Only IPv4 and IPv6 addresses are supported"); +} +function starMatchToRegex(pattern) { + const source14 = pattern.split("*").map((s) => { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + }).join(".*"); + return new RegExp("^" + source14 + "$"); +} +function parsePattern(pattern) { + if (!pattern) + return () => false; + const matchers = pattern.split(",").map((token) => { + const match = token.match(/^(.*?)(?::(\d+))?$/); + if (!match) + throw new Error(`Unsupported token "${token}" in pattern "${pattern}"`); + const tokenPort = match[2] ? +match[2] : void 0; + const portMatches = (port) => tokenPort === void 0 || tokenPort === port; + let tokenHost = match[1]; + if (tokenHost === "") { + return (host, port) => { + if (!portMatches(port)) + return false; + return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]"; + }; + } + if (tokenHost === "*") + return (host, port) => portMatches(port); + if (import_net2.default.isIPv4(tokenHost) || import_net2.default.isIPv6(tokenHost)) + return (host, port) => host === tokenHost && portMatches(port); + if (tokenHost[0] === ".") + tokenHost = "*" + tokenHost; + const tokenRegex = starMatchToRegex(tokenHost); + return (host, port) => { + if (!portMatches(port)) + return false; + if (import_net2.default.isIPv4(host) || import_net2.default.isIPv6(host)) + return false; + return !!host.match(tokenRegex); + }; + }); + return (host, port) => matchers.some((matcher) => matcher(host, port)); +} +var import_events, import_net2, SocksConnection, SocksProxy, SocksProxyHandler; +var init_socksProxy = __esm({ + "packages/utils/socksProxy.ts"() { + "use strict"; + import_events = __toESM(require("events")); + import_net2 = __toESM(require("net")); + init_assert(); + init_crypto(); + init_debugLogger(); + init_network(); + SocksConnection = class { + constructor(uid, socket, client) { + this._buffer = Buffer.from([]); + this._offset = 0; + this._fence = 0; + this._uid = uid; + this._socket = socket; + this._client = client; + this._boundOnData = this._onData.bind(this); + socket.on("data", this._boundOnData); + socket.on("close", () => this._onClose()); + socket.on("end", () => this._onClose()); + socket.on("error", () => this._onClose()); + this._run().catch(() => this._socket.end()); + } + async _run() { + assert(await this._authenticate()); + const { command, host, port } = await this._parseRequest(); + if (command !== 1 /* CONNECT */) { + this._writeBytes(Buffer.from([ + 5, + 7 /* CommandNotSupported */, + 0, + // RSV + 1, + // IPv4 + 0, + 0, + 0, + 0, + // Address + 0, + 0 + // Port + ])); + return; + } + this._socket.off("data", this._boundOnData); + this._client.onSocketRequested({ uid: this._uid, host, port }); + } + async _authenticate() { + const version3 = await this._readByte(); + assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3); + const nMethods = await this._readByte(); + assert(nMethods, "No authentication methods specified"); + const methods = await this._readBytes(nMethods); + for (const method2 of methods) { + if (method2 === 0) { + this._writeBytes(Buffer.from([version3, method2])); + return true; + } + } + this._writeBytes(Buffer.from([version3, 255 /* NO_ACCEPTABLE_METHODS */])); + return false; + } + async _parseRequest() { + const version3 = await this._readByte(); + assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3); + const command = await this._readByte(); + await this._readByte(); + const addressType = await this._readByte(); + let host = ""; + switch (addressType) { + case 1 /* IPv4 */: + host = (await this._readBytes(4)).join("."); + break; + case 3 /* FqName */: + const length = await this._readByte(); + host = (await this._readBytes(length)).toString(); + break; + case 4 /* IPv6 */: + const bytes = await this._readBytes(16); + const tokens = []; + for (let i = 0; i < 8; ++i) + tokens.push(bytes.readUInt16BE(i * 2).toString(16)); + host = tokens.join(":"); + break; + } + const port = (await this._readBytes(2)).readUInt16BE(0); + this._buffer = Buffer.from([]); + this._offset = 0; + this._fence = 0; + return { + command, + host, + port + }; + } + async _readByte() { + const buffer = await this._readBytes(1); + return buffer[0]; + } + async _readBytes(length) { + this._fence = this._offset + length; + if (!this._buffer || this._buffer.length < this._fence) + await new Promise((f) => this._fenceCallback = f); + this._offset += length; + return this._buffer.slice(this._offset - length, this._offset); + } + _writeBytes(buffer) { + if (this._socket.writable) + this._socket.write(buffer); + } + _onClose() { + this._client.onSocketClosed({ uid: this._uid }); + } + _onData(buffer) { + this._buffer = Buffer.concat([this._buffer, buffer]); + if (this._fenceCallback && this._buffer.length >= this._fence) { + const callback = this._fenceCallback; + this._fenceCallback = void 0; + callback(); + } + } + socketConnected(host, port) { + this._writeBytes(Buffer.from([ + 5, + 0 /* Succeeded */, + 0, + // RSV + ...ipToSocksAddress(host), + // ATYP, Address + port >> 8, + port & 255 + // Port + ])); + this._socket.on("data", (data) => this._client.onSocketData({ uid: this._uid, data })); + } + socketFailed(errorCode) { + const buffer = Buffer.from([ + 5, + 0, + 0, + // RSV + ...ipToSocksAddress("0.0.0.0"), + // ATYP, Address + 0, + 0 + // Port + ]); + switch (errorCode) { + case "ENOENT": + case "ENOTFOUND": + case "ETIMEDOUT": + case "EHOSTUNREACH": + buffer[1] = 4 /* HostUnreachable */; + break; + case "ENETUNREACH": + buffer[1] = 3 /* NetworkUnreachable */; + break; + case "ECONNREFUSED": + buffer[1] = 5 /* ConnectionRefused */; + break; + case "ERULESET": + buffer[1] = 2 /* NotAllowedByRuleSet */; + break; + } + this._writeBytes(buffer); + this._socket.end(); + } + sendData(data) { + this._socket.write(data); + } + end() { + this._socket.end(); + } + error(error) { + this._socket.destroy(new Error(error)); + } + }; + SocksProxy = class _SocksProxy extends import_events.default { + constructor() { + super(); + this._connections = /* @__PURE__ */ new Map(); + this._sockets = /* @__PURE__ */ new Set(); + this._closed = false; + this._patternMatcher = () => false; + this._directSockets = /* @__PURE__ */ new Map(); + this._server = new import_net2.default.Server((socket) => { + const uid = createGuid(); + const connection = new SocksConnection(uid, socket, this); + this._connections.set(uid, connection); + }); + this._server.on("connection", (socket) => { + if (this._closed) { + socket.destroy(); + return; + } + this._sockets.add(socket); + socket.once("close", () => this._sockets.delete(socket)); + }); + } + static { + this.Events = { + SocksRequested: "socksRequested", + SocksData: "socksData", + SocksClosed: "socksClosed" + }; + } + setPattern(pattern) { + try { + this._patternMatcher = parsePattern(pattern); + } catch (e) { + this._patternMatcher = () => false; + } + } + async _handleDirect(request2) { + try { + const socket = await createSocket(request2.host, request2.port); + socket.on("data", (data) => this._connections.get(request2.uid)?.sendData(data)); + socket.on("error", (error) => { + this._connections.get(request2.uid)?.error(error.message); + this._directSockets.delete(request2.uid); + }); + socket.on("end", () => { + this._connections.get(request2.uid)?.end(); + this._directSockets.delete(request2.uid); + }); + const localAddress = socket.localAddress; + const localPort = socket.localPort; + this._directSockets.set(request2.uid, socket); + this._connections.get(request2.uid)?.socketConnected(localAddress, localPort); + } catch (error) { + this._connections.get(request2.uid)?.socketFailed(error.code); + } + } + port() { + return this._port; + } + async listen(port, hostname) { + return new Promise((f) => { + this._server.listen(port, hostname, () => { + const port2 = this._server.address().port; + this._port = port2; + f(port2); + }); + }); + } + async close() { + if (this._closed) + return; + this._closed = true; + for (const socket of this._sockets) + socket.destroy(); + this._sockets.clear(); + await new Promise((f) => this._server.close(f)); + } + onSocketRequested(payload) { + if (!this._patternMatcher(payload.host, payload.port)) { + this._handleDirect(payload); + return; + } + this.emit(_SocksProxy.Events.SocksRequested, payload); + } + onSocketData(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.write(payload.data); + return; + } + this.emit(_SocksProxy.Events.SocksData, payload); + } + onSocketClosed(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.destroy(); + this._directSockets.delete(payload.uid); + return; + } + this.emit(_SocksProxy.Events.SocksClosed, payload); + } + socketConnected({ uid, host, port }) { + this._connections.get(uid)?.socketConnected(host, port); + } + socketFailed({ uid, errorCode }) { + this._connections.get(uid)?.socketFailed(errorCode); + } + sendSocketData({ uid, data }) { + this._connections.get(uid)?.sendData(data); + } + sendSocketEnd({ uid }) { + this._connections.get(uid)?.end(); + } + sendSocketError({ uid, error }) { + this._connections.get(uid)?.error(error); + } + }; + SocksProxyHandler = class _SocksProxyHandler extends import_events.default { + constructor(pattern, redirectPortForTest) { + super(); + this._sockets = /* @__PURE__ */ new Map(); + this._patternMatcher = () => false; + this._patternMatcher = parsePattern(pattern); + this._redirectPortForTest = redirectPortForTest; + } + static { + this.Events = { + SocksConnected: "socksConnected", + SocksData: "socksData", + SocksError: "socksError", + SocksFailed: "socksFailed", + SocksEnd: "socksEnd" + }; + } + cleanup() { + for (const uid of this._sockets.keys()) + this.socketClosed({ uid }); + } + async socketRequested({ uid, host, port }) { + debugLogger.log("socks", `[${uid}] => request ${host}:${port}`); + if (!this._patternMatcher(host, port)) { + const payload = { uid, errorCode: "ERULESET" }; + debugLogger.log("socks", `[${uid}] <= pattern error ${payload.errorCode}`); + this.emit(_SocksProxyHandler.Events.SocksFailed, payload); + return; + } + if (host === "local.playwright") + host = "localhost"; + try { + if (this._redirectPortForTest) + port = this._redirectPortForTest; + const socket = await createSocket(host, port); + socket.on("data", (data) => { + const payload2 = { uid, data }; + this.emit(_SocksProxyHandler.Events.SocksData, payload2); + }); + socket.on("error", (error) => { + const payload2 = { uid, error: error.message }; + debugLogger.log("socks", `[${uid}] <= network socket error ${payload2.error}`); + this.emit(_SocksProxyHandler.Events.SocksError, payload2); + this._sockets.delete(uid); + }); + socket.on("end", () => { + const payload2 = { uid }; + debugLogger.log("socks", `[${uid}] <= network socket closed`); + this.emit(_SocksProxyHandler.Events.SocksEnd, payload2); + this._sockets.delete(uid); + }); + const localAddress = socket.localAddress; + const localPort = socket.localPort; + this._sockets.set(uid, socket); + const payload = { uid, host: localAddress, port: localPort }; + debugLogger.log("socks", `[${uid}] <= connected to network ${payload.host}:${payload.port}`); + this.emit(_SocksProxyHandler.Events.SocksConnected, payload); + } catch (error) { + const payload = { uid, errorCode: error.code }; + debugLogger.log("socks", `[${uid}] <= connect error ${payload.errorCode}`); + this.emit(_SocksProxyHandler.Events.SocksFailed, payload); + } + } + sendSocketData({ uid, data }) { + this._sockets.get(uid)?.write(data); + } + socketClosed({ uid }) { + debugLogger.log("socks", `[${uid}] <= browser socket closed`); + this._sockets.get(uid)?.destroy(); + this._sockets.delete(uid); + } + }; + } +}); + +// packages/utils/stringWidth.ts +function characterWidth(c) { + return getEastAsianWidth.eastAsianWidth(c.codePointAt(0)); +} +function stringWidth(v) { + let width = 0; + for (const { segment } of new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v)) + width += characterWidth(segment); + return width; +} +function suffixOfWidth(v, width) { + const segments = [...new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v)]; + let suffixBegin = v.length; + for (const { segment, index } of segments.reverse()) { + const segmentWidth = stringWidth(segment); + if (segmentWidth > width) + break; + width -= segmentWidth; + suffixBegin = index; + } + return v.substring(suffixBegin); +} +function fitToWidth(line, width, prefix) { + const prefixLength = prefix ? stripAnsiEscapes(prefix).length : 0; + width -= prefixLength; + if (stringWidth(line) <= width) + return line; + const parts = line.split(ansiRegex); + const taken = []; + for (let i = parts.length - 1; i >= 0; i--) { + if (i % 2) { + taken.push(parts[i]); + } else { + let part = suffixOfWidth(parts[i], width); + const wasTruncated = part.length < parts[i].length; + if (wasTruncated && parts[i].length > 0) { + part = "\u2026" + suffixOfWidth(parts[i], width - 1); + } + taken.push(part); + width -= stringWidth(part); + } + } + return taken.reverse().join(""); +} +var getEastAsianWidth; +var init_stringWidth = __esm({ + "packages/utils/stringWidth.ts"() { + "use strict"; + init_stringUtils(); + getEastAsianWidth = require("./utilsBundle").getEastAsianWidth; + } +}); + +// packages/utils/wsServer.ts +var wsServer2, lastConnectionId, kConnectionSymbol, perMessageDeflate, WSServer; +var init_wsServer = __esm({ + "packages/utils/wsServer.ts"() { + "use strict"; + init_httpServer(); + init_network(); + init_debugLogger(); + ({ wsServer: wsServer2 } = require("./utilsBundle")); + lastConnectionId = 0; + kConnectionSymbol = /* @__PURE__ */ Symbol("kConnection"); + perMessageDeflate = { + serverNoContextTakeover: true, + zlibDeflateOptions: { + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + threshold: 10 * 1024 + }; + WSServer = class { + constructor(delegate) { + // Allowed Host headers for HTTP requests. null disables the check (server bound to a public address). + this._allowedHosts = null; + this._delegate = delegate; + } + async listen(port = 0, hostname, defaultPath) { + debugLogger.log("server", `Server started at ${/* @__PURE__ */ new Date()}`); + hostname ??= "localhost"; + const server = createHttpServer((request2, response2) => this._onRequest(request2, response2)); + server.on("error", (error) => debugLogger.log("server", String(error))); + this.server = server; + const wsEndpoint = await new Promise((resolve, reject) => { + server.listen(port, hostname, () => { + const address = server.address(); + if (!address) { + reject(new Error("Could not bind server socket")); + return; + } + if (typeof address === "string") { + resolve(`${address}${defaultPath}`); + return; + } + this._allowedHosts = computeAllowedHosts(hostname, address.address); + resolve(`ws://${urlHostFromAddress(address)}:${address.port}${defaultPath}`); + }).on("error", reject); + }); + debugLogger.log("server", "Listening at " + wsEndpoint); + this._wsServer = new wsServer2({ + noServer: true, + perMessageDeflate + }); + this._wsServer.on("headers", (headers) => this._delegate.onHeaders(headers)); + server.on("upgrade", (request2, socket, head) => { + const pathname = new URL("http://localhost" + request2.url).pathname; + if (!this._delegate.isAllowedPathname(pathname)) { + socket.write(`HTTP/${request2.httpVersion} 400 Bad Request\r +\r +`); + socket.destroy(); + return; + } + if (!isAllowedHost(request2, this._allowedHosts) || !this._isAllowedOrigin(request2.headers.origin)) { + socket.write(`HTTP/${request2.httpVersion} 403 Forbidden\r +\r +`); + socket.destroy(); + return; + } + const upgradeResult = this._delegate.onUpgrade(request2, socket); + if (upgradeResult) { + socket.write(upgradeResult.error); + socket.destroy(); + return; + } + this._wsServer.handleUpgrade(request2, socket, head, (ws4) => this._wsServer.emit("connection", ws4, request2)); + }); + this._wsServer.on("connection", (ws4, request2) => { + debugLogger.log("server", "Connected client ws.extension=" + ws4.extensions); + const url3 = new URL("http://localhost" + (request2.url || "")); + const id = String(++lastConnectionId); + debugLogger.log("server", `[${id}] serving connection: ${request2.url}`); + const connection = this._delegate.onConnection(request2, url3, ws4, id); + ws4[kConnectionSymbol] = connection; + }); + return wsEndpoint; + } + _onRequest(request2, response2) { + if (!isAllowedHost(request2, this._allowedHosts)) { + response2.statusCode = 403; + response2.end(); + return; + } + this._delegate.onRequest(request2, response2); + } + _isAllowedOrigin(origin) { + if (!this._allowedHosts || !origin) + return true; + try { + const url3 = new URL(origin); + if (url3.protocol !== "http:" && url3.protocol !== "https:") + return true; + const hostname = url3.hostname.toLowerCase(); + const bracketed = hostname.includes(":") ? `[${hostname}]` : hostname; + return this._allowedHosts.has(hostname) || this._allowedHosts.has(bracketed); + } catch { + return false; + } + } + async close() { + const server = this._wsServer; + if (!server) + return; + debugLogger.log("server", "closing websocket server"); + const waitForClose = new Promise((f) => server.close(f)); + await Promise.all(Array.from(server.clients).map(async (ws4) => { + const connection = ws4[kConnectionSymbol]; + if (connection) + await connection.close(); + try { + ws4.terminate(); + } catch (e) { + } + })); + await waitForClose; + debugLogger.log("server", "closing http server"); + if (this.server) + await new Promise((f) => this.server.close(f)); + this._wsServer = void 0; + this.server = void 0; + debugLogger.log("server", "closed server"); + } + }; + } +}); + +// packages/utils/zipFile.ts +var yauzl, ZipFile; +var init_zipFile = __esm({ + "packages/utils/zipFile.ts"() { + "use strict"; + yauzl = require("./utilsBundle").yauzl; + ZipFile = class { + constructor(fileName) { + this._entries = /* @__PURE__ */ new Map(); + this._fileName = fileName; + this._openedPromise = this._open(); + } + async _open() { + await new Promise((fulfill, reject) => { + yauzl.open(this._fileName, { autoClose: false }, (e, z35) => { + if (e) { + reject(e); + return; + } + this._zipFile = z35; + this._zipFile.on("entry", (entry) => { + this._entries.set(entry.fileName, entry); + }); + this._zipFile.on("end", fulfill); + }); + }); + } + async entries() { + await this._openedPromise; + return [...this._entries.keys()]; + } + async read(entryPath) { + await this._openedPromise; + const entry = this._entries.get(entryPath); + if (!entry) + throw new Error(`${entryPath} not found in file ${this._fileName}`); + return new Promise((resolve, reject) => { + this._zipFile.openReadStream(entry, (error, readStream) => { + if (error || !readStream) { + reject(error || "Entry not found"); + return; + } + const buffers = []; + readStream.on("data", (data) => buffers.push(data)); + readStream.on("end", () => resolve(Buffer.concat(buffers))); + }); + }); + } + close() { + this._zipFile?.close(); + } + }; + } +}); + +// packages/utils/zones.ts +function currentZone() { + return asyncLocalStorage.getStore() ?? emptyZone; +} +var import_async_hooks, asyncLocalStorage, Zone, emptyZone; +var init_zones = __esm({ + "packages/utils/zones.ts"() { + "use strict"; + import_async_hooks = require("async_hooks"); + asyncLocalStorage = new import_async_hooks.AsyncLocalStorage(); + Zone = class _Zone { + constructor(asyncLocalStorage2, store) { + this._asyncLocalStorage = asyncLocalStorage2; + this._data = store; + } + with(type3, data) { + return new _Zone(this._asyncLocalStorage, new Map(this._data).set(type3, data)); + } + without(type3) { + const data = type3 ? new Map(this._data) : /* @__PURE__ */ new Map(); + data.delete(type3); + return new _Zone(this._asyncLocalStorage, data); + } + run(func) { + return this._asyncLocalStorage.run(this, func); + } + data(type3) { + return this._data.get(type3); + } + }; + emptyZone = new Zone(asyncLocalStorage, /* @__PURE__ */ new Map()); + } +}); + +// packages/utils/third_party/extractZip.ts +async function extractZip(zipPath, opts) { + debug2("creating target directory", opts.dir); + if (!import_path6.default.isAbsolute(opts.dir)) + throw new Error("Target directory is expected to be absolute"); + await import_fs8.promises.mkdir(opts.dir, { recursive: true }); + opts.dir = await import_fs8.promises.realpath(opts.dir); + return new Extractor(zipPath, opts).extract(); +} +var import_fs8, import_path6, import_stream, import_util, debugPkg, getStream, yauzl2, debug2, openZip, pipeline, Extractor; +var init_extractZip = __esm({ + "packages/utils/third_party/extractZip.ts"() { + "use strict"; + import_fs8 = require("fs"); + import_path6 = __toESM(require("path")); + import_stream = __toESM(require("stream")); + import_util = require("util"); + debugPkg = require("./utilsBundle").debug; + getStream = require("./utilsBundle").getStream; + yauzl2 = require("./utilsBundle").yauzl; + debug2 = debugPkg("extract-zip"); + openZip = (0, import_util.promisify)(yauzl2.open); + pipeline = (0, import_util.promisify)(import_stream.default.pipeline); + Extractor = class { + constructor(zipPath, opts) { + this.canceled = false; + this.zipPath = zipPath; + this.opts = opts; + } + async extract() { + debug2("opening", this.zipPath, "with opts", this.opts); + this.zipfile = await openZip(this.zipPath, { lazyEntries: true }); + this.canceled = false; + return new Promise((resolve, reject) => { + this.zipfile.on("error", (err) => { + this.canceled = true; + reject(err); + }); + this.zipfile.readEntry(); + this.zipfile.on("close", () => { + if (!this.canceled) { + debug2("zip extraction complete"); + resolve(); + } + }); + this.zipfile.on("entry", async (entry) => { + if (this.canceled) { + debug2("skipping entry", entry.fileName, { cancelled: this.canceled }); + return; + } + debug2("zipfile entry", entry.fileName); + if (entry.fileName.startsWith("__MACOSX/")) { + this.zipfile.readEntry(); + return; + } + const destDir = import_path6.default.dirname(import_path6.default.join(this.opts.dir, entry.fileName)); + try { + await import_fs8.promises.mkdir(destDir, { recursive: true }); + const canonicalDestDir = await import_fs8.promises.realpath(destDir); + const relativeDestDir = import_path6.default.relative(this.opts.dir, canonicalDestDir); + if (relativeDestDir.split(import_path6.default.sep).includes("..")) + throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`); + await this.extractEntry(entry); + debug2("finished processing", entry.fileName); + this.zipfile.readEntry(); + } catch (err) { + this.canceled = true; + this.zipfile.close(); + reject(err); + } + }); + }); + } + async extractEntry(entry) { + if (this.canceled) { + debug2("skipping entry extraction", entry.fileName, { cancelled: this.canceled }); + return; + } + if (this.opts.onEntry) + this.opts.onEntry(entry, this.zipfile); + const dest = import_path6.default.join(this.opts.dir, entry.fileName); + const mode = entry.externalFileAttributes >> 16 & 65535; + const IFMT = 61440; + const IFDIR = 16384; + const IFLNK = 40960; + const symlink = (mode & IFMT) === IFLNK; + let isDir = (mode & IFMT) === IFDIR; + if (!isDir && entry.fileName.endsWith("/")) + isDir = true; + const madeBy = entry.versionMadeBy >> 8; + if (!isDir) + isDir = madeBy === 0 && entry.externalFileAttributes === 16; + debug2("extracting entry", { filename: entry.fileName, isDir, isSymlink: symlink }); + const procMode = this.getExtractedMode(mode, isDir) & 511; + const destDir = isDir ? dest : import_path6.default.dirname(dest); + const mkdirOptions = { recursive: true }; + if (isDir) + mkdirOptions.mode = procMode; + debug2("mkdir", { dir: destDir, ...mkdirOptions }); + await import_fs8.promises.mkdir(destDir, mkdirOptions); + if (isDir) + return; + debug2("opening read stream", dest); + const readStream = await (0, import_util.promisify)(this.zipfile.openReadStream.bind(this.zipfile))(entry); + if (symlink) { + const link = await getStream(readStream); + debug2("creating symlink", link, dest); + await import_fs8.promises.symlink(link, dest); + } else { + await pipeline(readStream, (0, import_fs8.createWriteStream)(dest, { mode: procMode })); + } + } + getExtractedMode(entryMode, isDir) { + let mode = entryMode; + if (mode === 0) { + if (isDir) { + if (this.opts.defaultDirMode) + mode = Number(this.opts.defaultDirMode); + if (!mode) + mode = 493; + } else { + if (this.opts.defaultFileMode) + mode = Number(this.opts.defaultFileMode); + if (!mode) + mode = 420; + } + } + return mode; + } + }; + } +}); + +// packages/utils/third_party/lockfile.ts +function probe(file, fs71, callback) { + const cachedPrecision = fs71[cacheSymbol]; + if (cachedPrecision) { + return fs71.stat(file, (err, stat) => { + if (err) + return callback(err); + callback(null, stat.mtime, cachedPrecision); + }); + } + const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5); + fs71.utimes(file, mtime, mtime, (err) => { + if (err) + return callback(err); + fs71.stat(file, (err2, stat) => { + if (err2) + return callback(err2); + const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms"; + Object.defineProperty(fs71, cacheSymbol, { value: precision }); + callback(null, stat.mtime, precision); + }); + }); +} +function getMtime(precision) { + let now = Date.now(); + if (precision === "s") + now = Math.ceil(now / 1e3) * 1e3; + return new Date(now); +} +function getLockFile(file, options) { + return options.lockfilePath || `${file}.lock`; +} +function resolveCanonicalPath(file, options, callback) { + if (!options.realpath) + return callback(null, import_path7.default.resolve(file)); + options.fs.realpath(file, callback); +} +function acquireLock(file, options, callback) { + const lockfilePath = getLockFile(file, options); + options.fs.mkdir(lockfilePath, (err) => { + if (!err) { + return probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision) => { + if (err2) { + options.fs.rmdir(lockfilePath, () => { + }); + return callback(err2); + } + callback(null, mtime, mtimePrecision); + }); + } + if (err.code !== "EEXIST") + return callback(err); + if (options.stale <= 0) + return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file })); + options.fs.stat(lockfilePath, (err2, stat) => { + if (err2) { + if (err2.code === "ENOENT") + return acquireLock(file, { ...options, stale: 0 }, callback); + return callback(err2); + } + if (!isLockStale(stat, options)) + return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file })); + removeLock(file, options, (err3) => { + if (err3) + return callback(err3); + acquireLock(file, { ...options, stale: 0 }, callback); + }); + }); + }); +} +function isLockStale(stat, options) { + return stat.mtime.getTime() < Date.now() - options.stale; +} +function removeLock(file, options, callback) { + options.fs.rmdir(getLockFile(file, options), (err) => { + if (err && err.code !== "ENOENT") + return callback(err); + callback(null); + }); +} +function updateLock(file, options) { + const lock2 = locks[file]; + if (lock2.updateTimeout) + return; + lock2.updateDelay = lock2.updateDelay || options.update; + lock2.updateTimeout = setTimeout(() => { + lock2.updateTimeout = null; + options.fs.stat(lock2.lockfilePath, (err, stat) => { + const isOverThreshold = lock2.lastUpdate + options.stale < Date.now(); + if (err) { + if (err.code === "ENOENT" || isOverThreshold) + return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" })); + lock2.updateDelay = 1e3; + return updateLock(file, options); + } + const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime(); + if (!isMtimeOurs) { + return setLockAsCompromised( + file, + lock2, + Object.assign( + new Error("Unable to update lock within the stale threshold"), + { code: "ECOMPROMISED" } + ) + ); + } + const mtime = getMtime(lock2.mtimePrecision); + options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => { + const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now(); + if (lock2.released) + return; + if (err2) { + if (err2.code === "ENOENT" || isOverThreshold2) + return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" })); + lock2.updateDelay = 1e3; + return updateLock(file, options); + } + lock2.mtime = mtime; + lock2.lastUpdate = Date.now(); + lock2.updateDelay = null; + updateLock(file, options); + }); + }); + }, lock2.updateDelay); + if (lock2.updateTimeout && lock2.updateTimeout.unref) + lock2.updateTimeout.unref(); +} +function setLockAsCompromised(file, lock2, err) { + lock2.released = true; + if (lock2.updateTimeout) + clearTimeout(lock2.updateTimeout); + if (locks[file] === lock2) + delete locks[file]; + lock2.options.onCompromised(err); +} +function lockImpl(file, options, callback) { + const resolvedOptions = { + stale: 1e4, + update: null, + realpath: true, + retries: 0, + fs: gracefulFs, + onCompromised: (err) => { + throw err; + }, + ...options + }; + resolvedOptions.retries = resolvedOptions.retries || 0; + resolvedOptions.retries = typeof resolvedOptions.retries === "number" ? { retries: resolvedOptions.retries } : resolvedOptions.retries; + resolvedOptions.stale = Math.max(resolvedOptions.stale || 0, 2e3); + resolvedOptions.update = resolvedOptions.update === null || resolvedOptions.update === void 0 ? resolvedOptions.stale / 2 : resolvedOptions.update || 0; + resolvedOptions.update = Math.max(Math.min(resolvedOptions.update, resolvedOptions.stale / 2), 1e3); + resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => { + if (err) + return callback(err); + const canonicalFile = resolvedFile; + const operation = retry.operation(resolvedOptions.retries); + operation.attempt(() => { + acquireLock(canonicalFile, resolvedOptions, (err2, mtime, mtimePrecision) => { + if (operation.retry(err2 || void 0)) + return; + if (err2) + return callback(operation.mainError()); + const lock2 = locks[canonicalFile] = { + lockfilePath: getLockFile(canonicalFile, resolvedOptions), + mtime, + mtimePrecision, + options: resolvedOptions, + lastUpdate: Date.now() + }; + updateLock(canonicalFile, resolvedOptions); + callback(null, (releasedCallback) => { + if (lock2.released) { + return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" })); + } + unlock(canonicalFile, { ...resolvedOptions, realpath: false }, releasedCallback || (() => { + })); + }); + }); + }); + }); +} +function unlock(file, options, callback) { + const resolvedOptions = { + stale: 1e4, + update: null, + realpath: true, + retries: 0, + fs: gracefulFs, + onCompromised: (err) => { + throw err; + }, + ...options + }; + resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => { + if (err) + return callback(err); + const canonicalFile = resolvedFile; + const lock2 = locks[canonicalFile]; + if (!lock2) + return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" })); + if (lock2.updateTimeout) + clearTimeout(lock2.updateTimeout); + lock2.released = true; + delete locks[canonicalFile]; + removeLock(canonicalFile, resolvedOptions, callback); + }); +} +function toPromise(method2) { + return (...args) => new Promise((resolve, reject) => { + args.push((err, result2) => { + if (err) + reject(err); + else + resolve(result2); + }); + method2(...args); + }); +} +function ensureCleanup() { + if (cleanupInitialized) + return; + cleanupInitialized = true; + onExit(() => { + for (const file in locks) { + const options = locks[file].options; + try { + options.fs.rmdirSync(getLockFile(file, options)); + } catch (e) { + } + } + }); +} +async function lock(file, options) { + ensureCleanup(); + const release = await toPromise(lockImpl)(file, options || {}); + return toPromise(release); +} +var import_path7, gracefulFs, retry, onExit, locks, cacheSymbol, cleanupInitialized; +var init_lockfile = __esm({ + "packages/utils/third_party/lockfile.ts"() { + "use strict"; + import_path7 = __toESM(require("path")); + gracefulFs = require("./utilsBundle").gracefulFs; + retry = require("./utilsBundle").retry; + ({ onExit } = require("./utilsBundle")); + locks = {}; + cacheSymbol = /* @__PURE__ */ Symbol(); + cleanupInitialized = false; + } +}); + +// packages/utils/index.ts +var utils_exports = {}; +__export(utils_exports, { + DER: () => DER, + FastStats: () => FastStats, + HttpServer: () => HttpServer, + ImageChannel: () => ImageChannel, + NET_DEFAULT_TIMEOUT: () => NET_DEFAULT_TIMEOUT, + RecentLogsCollector: () => RecentLogsCollector, + SerializedFS: () => SerializedFS, + SocksProxy: () => SocksProxy, + SocksProxyHandler: () => SocksProxyHandler, + WSServer: () => WSServer, + ZipFile: () => ZipFile, + Zone: () => Zone, + addSuffixToFilePath: () => addSuffixToFilePath, + blendWithWhite: () => blendWithWhite, + calculateSha1: () => calculateSha1, + canAccessFile: () => canAccessFile, + captureRawStack: () => captureRawStack, + colorDeltaE94: () => colorDeltaE94, + compare: () => compare, + compareBuffersOrStrings: () => compareBuffersOrStrings, + computeAllowedHosts: () => computeAllowedHosts, + copyFileAndMakeWritable: () => copyFileAndMakeWritable, + coreDir: () => coreDir, + createGuid: () => createGuid, + createHttp2Server: () => createHttp2Server, + createHttpServer: () => createHttpServer, + createHttpsServer: () => createHttpsServer, + createProxyAgent: () => createProxyAgent, + createSocket: () => createSocket, + currentZone: () => currentZone, + debugLogger: () => debugLogger, + debugMode: () => debugMode, + decodeWebp: () => decodeWebp, + decorateServer: () => decorateServer, + defaultUserDataDirForChannel: () => defaultUserDataDirForChannel, + emptyZone: () => emptyZone, + encodeWebp: () => encodeWebp, + envArrayToObject: () => envArrayToObject, + eventsHelper: () => eventsHelper, + existsAsync: () => existsAsync, + extractZip: () => extractZip, + filterStackFile: () => filterStackFile, + filteredStackTrace: () => filteredStackTrace, + fitToWidth: () => fitToWidth, + flattenAggregateError: () => flattenAggregateError, + generateSelfSignedCertificate: () => generateSelfSignedCertificate, + getAsBooleanFromENV: () => getAsBooleanFromENV, + getComparator: () => getComparator, + getFromENV: () => getFromENV, + getPackageManager: () => getPackageManager, + getPackageManagerExecCommand: () => getPackageManagerExecCommand, + gracefullyCloseAll: () => gracefullyCloseAll, + gracefullyCloseSet: () => gracefullyCloseSet, + gracefullyProcessExitDoNotHang: () => gracefullyProcessExitDoNotHang, + guessClientName: () => guessClientName, + happyEyeballsOptions: () => happyEyeballsOptions, + hostPlatform: () => hostPlatform, + httpRequest: () => httpRequest, + isAllowedHost: () => isAllowedHost, + isChromiumChannelName: () => isChromiumChannelName, + isCodingAgent: () => isCodingAgent, + isLikelyNpxGlobal: () => isLikelyNpxGlobal, + isLosslessWebp: () => isLosslessWebp, + isOfficiallySupportedPlatform: () => isOfficiallySupportedPlatform, + isPathInside: () => isPathInside, + isSystemDirectory: () => isSystemDirectory, + isURLAvailable: () => isURLAvailable, + isUnderTest: () => isUnderTest, + isWritable: () => isWritable, + jsonStringifyForceASCII: () => jsonStringifyForceASCII, + killProcessTree: () => killProcessTree, + launchProcess: () => launchProcess, + lock: () => lock, + makeSocketPath: () => makeSocketPath, + mkdirIfNeeded: () => mkdirIfNeeded, + parseErrorStack: () => parseErrorStack, + parsePattern: () => parsePattern, + parseStackFrame: () => parseStackFrame, + perMessageDeflate: () => perMessageDeflate, + proxySettingsFromString: () => proxySettingsFromString, + removeFolders: () => removeFolders, + resolveSymlinks: () => resolveSymlinks, + resolveWithinRoot: () => resolveWithinRoot, + rewriteErrorMessage: () => rewriteErrorMessage, + rgb2gray: () => rgb2gray, + sanitizeForFilePath: () => sanitizeForFilePath, + serveFolder: () => serveFolder, + setBoxedStackPrefixes: () => setBoxedStackPrefixes, + setCoreDir: () => setCoreDir, + setPlaywrightTestProcessEnv: () => setPlaywrightTestProcessEnv, + shortPlatform: () => shortPlatform, + showInternalStackFrames: () => showInternalStackFrames, + spawnAsync: () => spawnAsync, + splitErrorMessage: () => splitErrorMessage, + srgb2xyz: () => srgb2xyz, + ssim: () => ssim, + startHttpServer: () => startHttpServer, + stringWidth: () => stringWidth, + stringifyStackFrames: () => stringifyStackFrames, + throwingResolveWithinRoot: () => throwingResolveWithinRoot, + toPosixPath: () => toPosixPath, + trimLongString: () => trimLongString, + urlHostFromAddress: () => urlHostFromAddress, + wrapInASCIIBox: () => wrapInASCIIBox, + xyz2lab: () => xyz2lab +}); +var init_utils = __esm({ + "packages/utils/index.ts"() { + "use strict"; + init_ascii(); + init_chromiumChannels(); + init_comparators(); + init_crypto(); + init_debug(); + init_webp(); + init_debugLogger(); + init_env(); + init_eventsHelper(); + init_fileUtils(); + init_hostPlatform(); + init_httpServer(); + init_network(); + init_processLauncher(); + init_serializedFS(); + init_socksProxy(); + init_stackTrace(); + init_stringWidth(); + init_wsServer(); + init_zipFile(); + init_zones(); + init_extractZip(); + init_lockfile(); + init_colorUtils(); + init_compare(); + init_imageChannel(); + init_stats(); + } +}); + +// packages/playwright-core/src/client/eventEmitter.ts +function checkListener(listener) { + if (typeof listener !== "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); +} +function unwrapListener(l) { + return wrappedListener(l) ?? l; +} +function unwrapListeners(arr) { + return arr.map((l) => wrappedListener(l) ?? l); +} +function wrappedListener(l) { + return l.listener; +} +var import_events2, EventEmitter2, OnceWrapper; +var init_eventEmitter = __esm({ + "packages/playwright-core/src/client/eventEmitter.ts"() { + "use strict"; + import_events2 = require("events"); + init_debug(); + EventEmitter2 = class { + constructor() { + this._events = void 0; + this._eventsCount = 0; + this._maxListeners = void 0; + this._pendingHandlers = /* @__PURE__ */ new Map(); + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + this.on = this.addListener; + this.off = this.removeListener; + } + setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || Number.isNaN(n)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); + this._maxListeners = n; + return this; + } + getMaxListeners() { + return this._maxListeners === void 0 ? import_events2.EventEmitter.defaultMaxListeners : this._maxListeners; + } + emit(type3, ...args) { + const events = this._events; + if (events === void 0) + return false; + const handler = events?.[type3]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + this._callHandler(type3, handler, args); + } else { + const len = handler.length; + const listeners = handler.slice(); + for (let i = 0; i < len; ++i) + this._callHandler(type3, listeners[i], args); + } + return true; + } + _callHandler(type3, handler, args) { + const promise = Reflect.apply(handler, this, args); + if (!(promise instanceof Promise)) + return; + let set = this._pendingHandlers.get(type3); + if (!set) { + set = /* @__PURE__ */ new Set(); + this._pendingHandlers.set(type3, set); + } + set.add(promise); + promise.catch((e) => { + if (this._rejectionHandler) + this._rejectionHandler(e); + else + throw e; + }).finally(() => set.delete(promise)); + } + addListener(type3, listener) { + return this._addListener(type3, listener, false); + } + on(type3, listener) { + return this._addListener(type3, listener, false); + } + _addListener(type3, listener, prepend) { + checkListener(listener); + let events = this._events; + let existing; + if (events === void 0) { + events = this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else { + if (events.newListener !== void 0) { + this.emit("newListener", type3, unwrapListener(listener)); + events = this._events; + } + existing = events[type3]; + } + if (existing === void 0) { + existing = events[type3] = listener; + ++this._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type3] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + const m = this.getMaxListeners(); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + const w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type3) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = this; + w.type = type3; + w.count = existing.length; + if (!isUnderTest()) { + console.warn(w); + } + } + } + return this; + } + prependListener(type3, listener) { + return this._addListener(type3, listener, true); + } + once(type3, listener) { + checkListener(listener); + this.on(type3, new OnceWrapper(this, type3, listener).wrapperFunction); + return this; + } + prependOnceListener(type3, listener) { + checkListener(listener); + this.prependListener(type3, new OnceWrapper(this, type3, listener).wrapperFunction); + return this; + } + removeListener(type3, listener) { + checkListener(listener); + const events = this._events; + if (events === void 0) + return this; + const list = events[type3]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) { + this._events = /* @__PURE__ */ Object.create(null); + } else { + delete events[type3]; + if (events.removeListener) + this.emit("removeListener", type3, list.listener ?? listener); + } + } else if (typeof list !== "function") { + let position = -1; + let originalListener; + for (let i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || wrappedListener(list[i]) === listener) { + originalListener = wrappedListener(list[i]); + position = i; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else + list.splice(position, 1); + if (list.length === 1) + events[type3] = list[0]; + if (events.removeListener !== void 0) + this.emit("removeListener", type3, originalListener || listener); + } + return this; + } + off(type3, listener) { + return this.removeListener(type3, listener); + } + removeAllListeners(type3, options) { + this._removeAllListeners(type3); + if (!options) + return this; + if (options.behavior === "wait") { + const errors = []; + this._rejectionHandler = (error) => errors.push(error); + return this._waitFor(type3).then(() => { + if (errors.length) + throw errors[0]; + }); + } + if (options.behavior === "ignoreErrors") + this._rejectionHandler = () => { + }; + return Promise.resolve(); + } + _removeAllListeners(type3) { + const events = this._events; + if (!events) + return; + if (!events.removeListener) { + if (type3 === void 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events[type3] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events[type3]; + } + return; + } + if (type3 === void 0) { + const keys = Object.keys(events); + let key; + for (let i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === "removeListener") + continue; + this._removeAllListeners(key); + } + this._removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return; + } + const listeners = events[type3]; + if (typeof listeners === "function") { + this.removeListener(type3, listeners); + } else if (listeners !== void 0) { + for (let i = listeners.length - 1; i >= 0; i--) + this.removeListener(type3, listeners[i]); + } + } + listeners(type3) { + return this._listeners(this, type3, true); + } + rawListeners(type3) { + return this._listeners(this, type3, false); + } + listenerCount(type3) { + const events = this._events; + if (events !== void 0) { + const listener = events[type3]; + if (typeof listener === "function") + return 1; + if (listener !== void 0) + return listener.length; + } + return 0; + } + eventNames() { + return this._eventsCount > 0 && this._events ? Reflect.ownKeys(this._events) : []; + } + async _waitFor(type3) { + let promises2 = []; + if (type3) { + promises2 = [...this._pendingHandlers.get(type3) || []]; + } else { + promises2 = []; + for (const [, pending] of this._pendingHandlers) + promises2.push(...pending); + } + await Promise.all(promises2); + } + _listeners(target, type3, unwrap) { + const events = target._events; + if (events === void 0) + return []; + const listener = events[type3]; + if (listener === void 0) + return []; + if (typeof listener === "function") + return unwrap ? [unwrapListener(listener)] : [listener]; + return unwrap ? unwrapListeners(listener) : listener.slice(); + } + }; + OnceWrapper = class { + constructor(eventEmitter, eventType, listener) { + this._fired = false; + this._eventEmitter = eventEmitter; + this._eventType = eventType; + this._listener = listener; + this.wrapperFunction = this._handle.bind(this); + this.wrapperFunction.listener = listener; + } + _handle(...args) { + if (this._fired) + return; + this._fired = true; + this._eventEmitter.removeListener(this._eventType, this.wrapperFunction); + return this._listener.apply(this._eventEmitter, args); + } + }; + } +}); + +// packages/playwright-core/src/package.ts +function libPath(...parts) { + return import_path8.default.join(packageRoot, "lib", ...parts); +} +var import_path8, packageRoot, packageJSON, binPath; +var init_package = __esm({ + "packages/playwright-core/src/package.ts"() { + "use strict"; + import_path8 = __toESM(require("path")); + packageRoot = import_path8.default.join(__dirname, ".."); + packageJSON = require(import_path8.default.join(packageRoot, "package.json")); + binPath = import_path8.default.join(packageRoot, "bin"); + } +}); + +// packages/playwright-core/src/tools/trace/traceParser.ts +async function extractTrace(traceFile, outDir) { + const zipFile = new ZipFile(traceFile); + try { + const entries = await zipFile.entries(); + for (const entry of entries) { + const outPath = resolveWithinRoot(outDir, entry); + if (!outPath) + throw new Error(`Trace entry '${entry}' escapes output directory`); + await import_fs9.default.promises.mkdir(import_path9.default.dirname(outPath), { recursive: true }); + const buffer = await zipFile.read(entry); + await import_fs9.default.promises.writeFile(outPath, buffer); + } + } finally { + zipFile.close(); + } +} +var import_fs9, import_path9, DirTraceLoaderBackend; +var init_traceParser = __esm({ + "packages/playwright-core/src/tools/trace/traceParser.ts"() { + "use strict"; + import_fs9 = __toESM(require("fs")); + import_path9 = __toESM(require("path")); + init_fileUtils(); + init_zipFile(); + DirTraceLoaderBackend = class { + constructor(dir) { + this._dir = dir; + } + isLive() { + return false; + } + async entryNames() { + const entries = []; + const walk = async (dir, prefix) => { + const items = await import_fs9.default.promises.readdir(dir, { withFileTypes: true }); + for (const item of items) { + if (item.isDirectory()) + await walk(import_path9.default.join(dir, item.name), prefix ? `${prefix}/${item.name}` : item.name); + else + entries.push(prefix ? `${prefix}/${item.name}` : item.name); + } + }; + await walk(this._dir, ""); + return entries; + } + async hasEntry(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return false; + try { + await import_fs9.default.promises.access(resolved); + return true; + } catch { + return false; + } + } + async readText(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return; + try { + return await import_fs9.default.promises.readFile(resolved, "utf-8"); + } catch { + } + } + async readBlob(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return; + try { + const buffer = await import_fs9.default.promises.readFile(resolved); + return new Blob([new Uint8Array(buffer)]); + } catch { + } + } + }; + } +}); + +// packages/playwright-core/src/tools/trace/traceUtils.ts +function ensureTraceOpen() { + if (!import_fs10.default.existsSync(traceDir)) + throw new Error(`No trace opened. Run 'npx playwright trace open ' first.`); + return traceDir; +} +async function closeTrace() { + if (import_fs10.default.existsSync(traceDir)) + await import_fs10.default.promises.rm(traceDir, { recursive: true }); +} +async function openTrace(traceFile) { + const filePath = import_path10.default.resolve(traceFile); + if (!import_fs10.default.existsSync(filePath)) + throw new Error(`Trace file not found: ${filePath}`); + await closeTrace(); + await import_fs10.default.promises.mkdir(traceDir, { recursive: true }); + if (filePath.endsWith(".zip")) + await extractTrace(filePath, traceDir); + else + await import_fs10.default.promises.writeFile(import_path10.default.join(traceDir, ".link"), filePath, "utf-8"); +} +async function loadTrace() { + const dir = ensureTraceOpen(); + const linkFile = import_path10.default.join(dir, ".link"); + let traceDir2; + let traceFile; + if (import_fs10.default.existsSync(linkFile)) { + const tracePath = await import_fs10.default.promises.readFile(linkFile, "utf-8"); + traceDir2 = import_path10.default.dirname(tracePath); + traceFile = import_path10.default.basename(tracePath); + } else { + traceDir2 = dir; + } + const backend = new DirTraceLoaderBackend(traceDir2); + const loader = new TraceLoader(); + await loader.load(backend, traceFile); + const model = new TraceModel(traceDir2, loader.contextEntries); + return new LoadedTrace(model, loader, buildOrdinalMap(model)); +} +function formatTimestamp(ms, base) { + const relative = ms - base; + if (relative < 0) + return "0:00.000"; + const totalMs = Math.floor(relative); + const minutes = Math.floor(totalMs / 6e4); + const seconds = Math.floor(totalMs % 6e4 / 1e3); + const millis = totalMs % 1e3; + return `${minutes}:${seconds.toString().padStart(2, "0")}.${millis.toString().padStart(3, "0")}`; +} +function actionTitle(action) { + return renderTitleForCall({ ...action, type: action.class }) || `${action.class}.${action.method}`; +} +function actionSubtitle(action) { + return renderSubtitleForCall({ ...action, type: action.class }); +} +function actionFullTitle(action) { + return renderFullTitleForCall({ ...action, type: action.class }) || `${action.class}.${action.method}`; +} +async function saveOutputFile(fileName, content, explicitOutput) { + let outFile; + if (explicitOutput) { + outFile = explicitOutput; + } else { + const resolved = resolveWithinRoot(cliOutputDir, fileName); + if (!resolved) + throw new Error(`Attachment name '${fileName}' escapes output directory`); + await import_fs10.default.promises.mkdir(import_path10.default.dirname(resolved), { recursive: true }); + outFile = resolved; + } + await import_fs10.default.promises.writeFile(outFile, content); + return outFile; +} +function buildOrdinalMap(model) { + const actions = model.actions.filter((a) => a.group !== "configuration"); + const { rootItem } = buildActionTree(actions); + const ordinalToCallId = /* @__PURE__ */ new Map(); + const callIdToOrdinal = /* @__PURE__ */ new Map(); + let ordinal = 1; + const visit = (item) => { + ordinalToCallId.set(ordinal, item.action.callId); + callIdToOrdinal.set(item.action.callId, ordinal); + ordinal++; + for (const child of item.children) + visit(child); + }; + for (const child of rootItem.children) + visit(child); + return { ordinalToCallId, callIdToOrdinal }; +} +var import_fs10, import_path10, traceDir, cliOutputDir, LoadedTrace, kActionPhases; +var init_traceUtils2 = __esm({ + "packages/playwright-core/src/tools/trace/traceUtils.ts"() { + "use strict"; + import_fs10 = __toESM(require("fs")); + import_path10 = __toESM(require("path")); + init_traceModel(); + init_traceLoader(); + init_protocolFormatter(); + init_fileUtils(); + init_traceParser(); + traceDir = import_path10.default.join(".playwright-cli", "trace"); + cliOutputDir = ".playwright-cli"; + LoadedTrace = class { + constructor(model, loader, ordinals) { + this.model = model; + this.loader = loader; + this.ordinalToCallId = ordinals.ordinalToCallId; + this.callIdToOrdinal = ordinals.callIdToOrdinal; + } + resolveActionId(actionId) { + const ordinal = parseInt(actionId, 10); + if (!isNaN(ordinal)) { + const callId = this.ordinalToCallId.get(ordinal); + if (callId) + return this.model.actions.find((a) => a.callId === callId); + } + return this.model.actions.find((a) => a.callId === actionId); + } + }; + kActionPhases = ["before", "action", "after"]; + } +}); + +// packages/playwright-core/src/tools/trace/traceOpen.ts +async function traceOpen(traceFile) { + await openTrace(traceFile); + await traceInfo(); +} +async function traceInfo() { + const trace = await loadTrace(); + const model = trace.model; + const info = { + browser: model.browserName || "unknown", + platform: model.platform || "unknown", + playwrightVersion: model.playwrightVersion || "unknown", + title: model.title || "", + duration: msToString(model.endTime - model.startTime), + durationMs: model.endTime - model.startTime, + startTime: model.wallTime ? new Date(model.wallTime).toISOString() : "unknown", + viewport: model.options.viewport ? `${model.options.viewport.width}x${model.options.viewport.height}` : "default", + actions: model.actions.length, + pages: model.pages.length, + network: model.resources.length, + errors: model.errorDescriptors.length, + attachments: model.attachments.length, + consoleMessages: model.events.filter((e) => e.type === "console").length + }; + console.log(""); + console.log(` Browser: ${info.browser}`); + console.log(` Platform: ${info.platform}`); + console.log(` Playwright: ${info.playwrightVersion}`); + if (info.title) + console.log(` Title: ${info.title}`); + console.log(` Duration: ${info.duration}`); + console.log(` Start time: ${info.startTime}`); + console.log(` Viewport: ${info.viewport}`); + console.log(` Actions: ${info.actions}`); + console.log(` Pages: ${info.pages}`); + console.log(` Network: ${info.network} requests`); + console.log(` Errors: ${info.errors}`); + console.log(` Attachments: ${info.attachments}`); + console.log(` Console: ${info.consoleMessages} messages`); + console.log(""); +} +var init_traceOpen = __esm({ + "packages/playwright-core/src/tools/trace/traceOpen.ts"() { + "use strict"; + init_formatUtils(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceActions.ts +async function traceActions(options) { + const trace = await loadTrace(); + const actions = filterActions(trace.model.actions, options); + const { rootItem } = buildActionTree(actions); + console.log(` ${"#".padStart(4)} ${"Time".padEnd(9)} ${"Action".padEnd(55)} ${"Duration".padStart(8)}`); + console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(9)} ${"\u2500".repeat(55)} ${"\u2500".repeat(8)}`); + const visit = (item, indent2) => { + const action = item.action; + const ordinal = trace.callIdToOrdinal.get(action.callId) ?? "?"; + const ts = formatTimestamp(action.startTime, trace.model.startTime); + const duration = action.endTime ? msToString(action.endTime - action.startTime) : "running"; + const title = actionTitle(action); + const subtitle = actionSubtitle(action); + const error = action.error ? " \u2717" : ""; + const prefix = ` ${(ordinal + ".").padStart(4)} ${ts} ${indent2}`; + console.log(`${prefix}${title.padEnd(Math.max(1, 55 - indent2.length))} ${duration.padStart(8)}${error}`); + if (subtitle) + console.log(`${" ".repeat(prefix.length)}${subtitle}`); + for (const child of item.children) + visit(child, indent2 + " "); + }; + for (const child of rootItem.children) + visit(child, ""); +} +function filterActions(actions, options) { + let result2 = actions.filter((a) => a.group !== "configuration"); + if (options.grep) { + const pattern = new RegExp(options.grep, "i"); + result2 = result2.filter((a) => pattern.test(actionFullTitle(a))); + } + if (options.errorsOnly) + result2 = result2.filter((a) => !!a.error); + return result2; +} +async function traceAction(actionId) { + const trace = await loadTrace(); + const action = trace.resolveActionId(actionId); + if (!action) { + console.error(`Action '${actionId}' not found. Use 'trace actions' to see available action IDs.`); + process.exitCode = 1; + return; + } + const title = actionFullTitle(action); + console.log(` + ${title} +`); + console.log(" Time"); + console.log(` start: ${formatTimestamp(action.startTime, trace.model.startTime)}`); + const duration = action.endTime ? msToString(action.endTime - action.startTime) : action.error ? "Timed Out" : "Running"; + console.log(` duration: ${duration}`); + const paramKeys = Object.keys(action.params).filter((name) => name !== "info"); + if (paramKeys.length) { + console.log("\n Parameters"); + for (const key of paramKeys) { + const value2 = formatParamValue(action.params[key]); + console.log(` ${key}: ${value2}`); + } + } + if (action.result) { + console.log("\n Return value"); + for (const [key, value2] of Object.entries(action.result)) + console.log(` ${key}: ${formatParamValue(value2)}`); + } + if (action.error) { + console.log("\n Error"); + console.log(` ${action.error.message}`); + } + if (action.log.length) { + console.log("\n Log"); + for (const entry of action.log) { + const time = entry.time !== -1 ? formatTimestamp(entry.time, trace.model.startTime) : ""; + console.log(` ${time.padEnd(12)} ${entry.message}`); + } + } + if (action.stack?.length) { + console.log("\n Source"); + for (const frame of action.stack.slice(0, 5)) { + const file = frame.file.replace(/.*[/\\](.*)/, "$1"); + console.log(` ${file}:${frame.line}:${frame.column}`); + } + } + const phases = kActionPhases.filter((phase) => trace.model.hasDomSnapshotForCall(action.callId, phase)); + if (phases.length) { + console.log("\n Snapshots"); + console.log(` available: ${phases.join(", ")}`); + console.log(` usage: npx playwright trace snapshot ${actionId} --phase <${phases.join("|")}>`); + } + console.log(""); +} +function formatParamValue(value2) { + if (value2 === void 0 || value2 === null) + return String(value2); + if (typeof value2 === "string") + return `"${value2}"`; + if (typeof value2 !== "object") + return String(value2); + if (value2.guid) + return ""; + return JSON.stringify(value2).slice(0, 1e3); +} +var init_traceActions = __esm({ + "packages/playwright-core/src/tools/trace/traceActions.ts"() { + "use strict"; + init_traceModel(); + init_formatUtils(); + init_traceUtils2(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceRequests.ts +async function traceRequests(options) { + const trace = await loadTrace(); + const model = trace.model; + let indexed = model.resources.map((r, i) => ({ resource: r, ordinal: i + 1 })); + if (options.grep) { + const pattern = new RegExp(options.grep, "i"); + indexed = indexed.filter(({ resource: r }) => pattern.test(r.request.url)); + } + if (options.method) + indexed = indexed.filter(({ resource: r }) => r.request.method.toLowerCase() === options.method.toLowerCase()); + if (options.status) { + const code = parseInt(options.status, 10); + indexed = indexed.filter(({ resource: r }) => r.response.status === code); + } + if (options.failed) + indexed = indexed.filter(({ resource: r }) => r.response.status >= 400 || r.response.status === -1); + if (!indexed.length) { + console.log(" No network requests"); + return; + } + console.log(` ${"#".padStart(4)} ${"Start".padEnd(9)} ${"Method".padEnd(8)} ${"Status".padEnd(8)} ${"Name".padEnd(45)} ${"Duration".padStart(10)} ${"Size".padStart(8)} ${"Route".padEnd(10)}`); + console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(9)} ${"\u2500".repeat(8)} ${"\u2500".repeat(8)} ${"\u2500".repeat(45)} ${"\u2500".repeat(10)} ${"\u2500".repeat(8)} ${"\u2500".repeat(10)}`); + for (const { resource: r, ordinal } of indexed) { + let name; + try { + const url3 = new URL(r.request.url); + name = url3.pathname.substring(url3.pathname.lastIndexOf("/") + 1); + if (!name) + name = url3.host; + if (url3.search) + name += url3.search; + } catch { + name = r.request.url; + } + if (name.length > 45) + name = name.substring(0, 42) + "..."; + const status = r.response.status > 0 ? String(r.response.status) : "ERR"; + const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize; + const route2 = formatRouteStatus(r); + const start3 = r._monotonicTime ? formatTimestamp(r._monotonicTime, model.startTime) : "-"; + console.log(` ${(ordinal + ".").padStart(4)} ${start3.padEnd(9)} ${r.request.method.padEnd(8)} ${status.padEnd(8)} ${name.padEnd(45)} ${msToString(r.time).padStart(10)} ${bytesToString2(size).padStart(8)} ${route2.padEnd(10)}`); + } +} +async function traceRequest(requestId) { + const trace = await loadTrace(); + const model = trace.model; + const ordinal = parseInt(requestId, 10); + const resource = !isNaN(ordinal) && ordinal >= 1 && ordinal <= model.resources.length ? model.resources[ordinal - 1] : void 0; + if (!resource) { + console.error(`Request '${requestId}' not found. Use 'trace requests' to see available request IDs.`); + process.exitCode = 1; + return; + } + const r = resource; + const status = r.response.status > 0 ? `${r.response.status} ${r.response.statusText}` : "ERR"; + const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize; + console.log(` + ${r.request.method} ${r.request.url} +`); + console.log(" General"); + console.log(` status: ${status}`); + if (r._monotonicTime) + console.log(` start: ${formatTimestamp(r._monotonicTime, model.startTime)}`); + console.log(` duration: ${msToString(r.time)}`); + console.log(` size: ${bytesToString2(size)}`); + if (r.response.content.mimeType) + console.log(` type: ${r.response.content.mimeType}`); + const route2 = formatRouteStatus(r); + if (route2) + console.log(` route: ${route2}`); + if (r.serverIPAddress) + console.log(` server: ${r.serverIPAddress}${r._serverPort ? ":" + r._serverPort : ""}`); + if (r.response._failureText) + console.log(` error: ${r.response._failureText}`); + if (r.request.headers.length) { + console.log("\n Request headers"); + for (const h of r.request.headers) + console.log(` ${h.name}: ${h.value}`); + } + if (r.request.postData) { + console.log("\n Request body"); + const resource2 = r.request.postData._file; + if (resource2) { + console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, resource2))}`); + } else { + const text2 = r.request.postData.text.length > 2e3 ? r.request.postData.text.substring(0, 2e3) + "..." : r.request.postData.text; + console.log(` ${text2}`); + } + } + if (r.response.headers.length) { + console.log("\n Response headers"); + for (const h of r.response.headers) + console.log(` ${h.name}: ${h.value}`); + } + if (r.response.bodySize > 0) { + const resource2 = r.response.content._file; + if (resource2) { + console.log("\n Response body"); + console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, resource2))}`); + } else if (r.response.content.text) { + const text2 = r.response.content.text.length > 2e3 ? r.response.content.text.substring(0, 2e3) + "..." : r.response.content.text; + console.log("\n Response body"); + console.log(` ${text2}`); + } + } + if (r._securityDetails) { + console.log("\n Security"); + if (r._securityDetails.protocol) + console.log(` protocol: ${r._securityDetails.protocol}`); + if (r._securityDetails.subjectName) + console.log(` subject: ${r._securityDetails.subjectName}`); + if (r._securityDetails.issuer) + console.log(` issuer: ${r._securityDetails.issuer}`); + } + console.log(""); +} +function bytesToString2(bytes) { + if (bytes < 0 || !isFinite(bytes)) + return "-"; + if (bytes === 0) + return "0"; + if (bytes < 1e3) + return bytes.toFixed(0); + const kb = bytes / 1024; + if (kb < 1e3) + return kb.toFixed(1) + "K"; + const mb = kb / 1024; + if (mb < 1e3) + return mb.toFixed(1) + "M"; + const gb = mb / 1024; + return gb.toFixed(1) + "G"; +} +function formatRouteStatus(r) { + if (r._wasAborted) + return "aborted"; + if (r._wasContinued) + return "continued"; + if (r._wasFulfilled) + return "fulfilled"; + if (r._apiRequestRef) + return "api"; + return ""; +} +var import_path11; +var init_traceRequests = __esm({ + "packages/playwright-core/src/tools/trace/traceRequests.ts"() { + "use strict"; + import_path11 = __toESM(require("path")); + init_formatUtils(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceConsole.ts +async function traceConsole(options) { + const trace = await loadTrace(); + const model = trace.model; + const items = []; + for (const event of model.events) { + if (event.type === "console") { + if (options.stdio) + continue; + const level = event.messageType; + if (options.errorsOnly && level !== "error") + continue; + if (options.warnings && level !== "error" && level !== "warning") + continue; + const url3 = event.location.url; + const filename = url3 ? url3.substring(url3.lastIndexOf("/") + 1) : ""; + items.push({ + type: "browser", + level, + text: event.text, + location: `${filename}:${event.location.lineNumber}`, + timestamp: event.time + }); + } + if (event.type === "event" && event.method === "pageError") { + if (options.stdio) + continue; + const error = event.params.error; + items.push({ + type: "browser", + level: "error", + text: error?.error?.message || String(error?.value || ""), + timestamp: event.time + }); + } + } + for (const event of model.stdio) { + if (options.browser) + continue; + if (options.errorsOnly && event.type !== "stderr") + continue; + if (options.warnings && event.type !== "stderr") + continue; + let text2 = ""; + if (event.text) + text2 = event.text.trim(); + if (event.base64) + text2 = Buffer.from(event.base64, "base64").toString("utf-8").trim(); + if (!text2) + continue; + items.push({ + type: event.type, + level: event.type === "stderr" ? "error" : "info", + text: text2, + timestamp: event.timestamp + }); + } + items.sort((a, b) => a.timestamp - b.timestamp); + let filtered = items; + if (options.grep) { + const pattern = new RegExp(options.grep, "i"); + filtered = filtered.filter((item) => pattern.test(item.text)); + } + if (!filtered.length) { + console.log(" No console entries"); + return; + } + for (const item of filtered) { + const ts = formatTimestamp(item.timestamp, model.startTime); + const source14 = item.type === "browser" ? "[browser]" : `[${item.type}]`; + const level = item.level.padEnd(8); + const location2 = item.location ? ` ${item.location}` : ""; + console.log(` ${ts} ${source14.padEnd(10)} ${level} ${item.text}${location2}`); + } +} +var init_traceConsole = __esm({ + "packages/playwright-core/src/tools/trace/traceConsole.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceErrors.ts +async function traceErrors() { + const trace = await loadTrace(); + const model = trace.model; + if (!model.errorDescriptors.length) { + console.log(" No errors"); + return; + } + for (const error of model.errorDescriptors) { + if (error.action) { + const title = actionFullTitle(error.action); + console.log(` + \u2717 ${title}`); + } else { + console.log(` + \u2717 Error`); + } + if (error.stack?.length) { + const frame = error.stack[0]; + const file = frame.file.replace(/.*[/\\](.*)/, "$1"); + console.log(` at ${file}:${frame.line}:${frame.column}`); + } + console.log(""); + const indented = error.message.split("\n").map((l) => ` ${l}`).join("\n"); + console.log(indented); + } + console.log(""); +} +var init_traceErrors = __esm({ + "packages/playwright-core/src/tools/trace/traceErrors.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/isomorphic/disposable.ts +async function disposeAll(disposables) { + const copy = [...disposables]; + disposables.length = 0; + await Promise.all(copy.map((d) => d.dispose())); +} +var init_disposable = __esm({ + "packages/isomorphic/disposable.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/server/userAgent.ts +function getUserAgent() { + if (cachedUserAgent) + return cachedUserAgent; + try { + cachedUserAgent = determineUserAgent(); + } catch (e) { + cachedUserAgent = "Playwright/unknown"; + } + return cachedUserAgent; +} +function determineUserAgent() { + let osIdentifier = "unknown"; + let osVersion = "unknown"; + if (process.platform === "win32") { + const version3 = import_os4.default.release().split("."); + osIdentifier = "windows"; + osVersion = `${version3[0]}.${version3[1]}`; + } else if (process.platform === "darwin") { + const version3 = (0, import_child_process.execSync)("sw_vers -productVersion", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim().split("."); + osIdentifier = "macOS"; + osVersion = `${version3[0]}.${version3[1]}`; + } else if (process.platform === "linux") { + const distroInfo = getLinuxDistributionInfoSync(); + if (distroInfo) { + osIdentifier = distroInfo.id || "linux"; + osVersion = distroInfo.version || "unknown"; + } else { + osIdentifier = "linux"; + } + } + const additionalTokens = []; + if (process.env.CI) + additionalTokens.push("CI/1"); + const serializedTokens = additionalTokens.length ? " " + additionalTokens.join(" ") : ""; + const { embedderName, embedderVersion } = getEmbedderName(); + return `Playwright/${getPlaywrightVersion()} (${import_os4.default.arch()}; ${osIdentifier} ${osVersion}) ${embedderName}/${embedderVersion}${serializedTokens}`; +} +function getEmbedderName() { + let embedderName = "unknown"; + let embedderVersion = "unknown"; + if (!process.env.PW_LANG_NAME) { + embedderName = "node"; + embedderVersion = process.version.substring(1).split(".").slice(0, 2).join("."); + } else if (["node", "python", "java", "csharp"].includes(process.env.PW_LANG_NAME)) { + embedderName = process.env.PW_LANG_NAME; + embedderVersion = process.env.PW_LANG_NAME_VERSION ?? "unknown"; + } + return { embedderName, embedderVersion }; +} +function getPlaywrightVersion(majorMinorOnly = false) { + const version3 = process.env.PW_VERSION_OVERRIDE || packageJSON.version; + return majorMinorOnly ? version3.split(".").slice(0, 2).join(".") : version3; +} +var import_child_process, import_os4, cachedUserAgent; +var init_userAgent = __esm({ + "packages/playwright-core/src/server/userAgent.ts"() { + "use strict"; + import_child_process = require("child_process"); + import_os4 = __toESM(require("os")); + init_linuxUtils(); + init_package(); + } +}); + +// packages/playwright-core/src/generated/clockSource.ts +var source; +var init_clockSource = __esm({ + "packages/playwright-core/src/generated/clockSource.ts"() { + "use strict"; + source = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/clock.ts\nvar clock_exports = {};\n__export(clock_exports, {\n ClockController: () => ClockController,\n createClock: () => createClock,\n inject: () => inject,\n install: () => install\n});\nmodule.exports = __toCommonJS(clock_exports);\nvar ClockController = class {\n constructor(embedder) {\n this._duringTick = false;\n this._uniqueTimerId = idCounterStart;\n this.disposables = [];\n this._log = [];\n this._timers = /* @__PURE__ */ new Map();\n this._now = { time: asWallTime(0), isFixedTime: false, ticks: 0, origin: asWallTime(-1) };\n this._embedder = embedder;\n }\n uninstall() {\n this.disposables.forEach((dispose) => dispose());\n this.disposables.length = 0;\n }\n now() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.time;\n }\n install(time) {\n this._replayLogOnce();\n this._innerInstall(asWallTime(time));\n }\n setSystemTime(time) {\n this._replayLogOnce();\n this._innerSetTime(asWallTime(time));\n }\n setFixedTime(time) {\n this._replayLogOnce();\n this._innerSetFixedTime(asWallTime(time));\n }\n performanceNow() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.ticks;\n }\n _syncRealTime() {\n if (!this._realTime)\n return;\n const now = this._embedder.performanceNow();\n const sinceLastSync = now - this._realTime.lastSyncTicks;\n if (sinceLastSync > 0) {\n this._advanceNow(shiftTicks(this._now.ticks, sinceLastSync));\n this._realTime.lastSyncTicks = now;\n }\n }\n _innerSetTime(time) {\n this._now.time = time;\n this._now.isFixedTime = false;\n if (this._now.origin < 0)\n this._now.origin = this._now.time;\n }\n _innerInstall(time) {\n if (this._now.origin < 0)\n this._now.ticks = 0;\n this._innerSetTime(time);\n }\n _innerSetFixedTime(time) {\n this._innerSetTime(time);\n this._now.isFixedTime = true;\n }\n _advanceNow(to) {\n if (this._now.ticks > to) {\n return;\n }\n if (!this._now.isFixedTime)\n this._now.time = asWallTime(this._now.time + to - this._now.ticks);\n this._now.ticks = to;\n }\n async log(type, time, param) {\n this._log.push({ type, time, param });\n }\n async runFor(ticks) {\n this._replayLogOnce();\n if (ticks < 0)\n throw new TypeError("Negative ticks are not supported");\n await this._runWithDisabledRealTimeSync(async () => {\n await this._runTo(shiftTicks(this._now.ticks, ticks));\n });\n }\n async _runTo(to) {\n to = Math.ceil(to);\n if (this._now.ticks > to)\n return;\n let firstException;\n while (true) {\n const result = await this._callFirstTimer(to);\n if (!result.timerFound)\n break;\n firstException = firstException || result.error;\n }\n this._advanceNow(to);\n if (firstException)\n throw firstException;\n }\n async pauseAt(time) {\n this._replayLogOnce();\n await this._innerPause();\n const toConsume = time - this._now.time;\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, toConsume));\n return toConsume;\n }\n async _innerPause() {\n var _a;\n this._realTime = void 0;\n await ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.dispose());\n this._currentRealTimeTimer = void 0;\n }\n resume() {\n this._replayLogOnce();\n this._innerResume();\n }\n _innerResume() {\n const now = this._embedder.performanceNow();\n this._realTime = { startTicks: now, lastSyncTicks: now };\n this._updateRealTimeTimer();\n }\n _updateRealTimeTimer() {\n var _a;\n if ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.promise) {\n return;\n }\n const firstTimer = this._firstTimer();\n const nextTick = Math.min(firstTimer ? firstTimer.callAt : this._now.ticks + maxTimeout, this._now.ticks + 100);\n const callAt = this._currentRealTimeTimer ? Math.min(this._currentRealTimeTimer.callAt, nextTick) : nextTick;\n if (this._currentRealTimeTimer) {\n this._currentRealTimeTimer.cancel();\n this._currentRealTimeTimer = void 0;\n }\n const realTimeTimer = {\n callAt,\n promise: void 0,\n cancel: this._embedder.setTimeout(() => {\n this._syncRealTime();\n realTimeTimer.promise = this._runTo(this._now.ticks).catch((e) => console.error(e));\n void realTimeTimer.promise.then(() => {\n this._currentRealTimeTimer = void 0;\n if (this._realTime)\n this._updateRealTimeTimer();\n });\n }, callAt - this._now.ticks),\n dispose: async () => {\n realTimeTimer.cancel();\n await realTimeTimer.promise;\n }\n };\n this._currentRealTimeTimer = realTimeTimer;\n }\n async _runWithDisabledRealTimeSync(fn) {\n if (!this._realTime) {\n await fn();\n return;\n }\n await this._innerPause();\n try {\n await fn();\n } finally {\n this._innerResume();\n }\n }\n async fastForward(ticks) {\n this._replayLogOnce();\n await this._runWithDisabledRealTimeSync(async () => {\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, ticks | 0));\n });\n }\n async _innerFastForwardTo(to) {\n if (to < this._now.ticks)\n throw new Error("Cannot fast-forward to the past");\n for (const timer of this._timers.values()) {\n if (to > timer.callAt)\n timer.callAt = to;\n }\n await this._runTo(to);\n }\n addTimer(options) {\n this._replayLogOnce();\n if (options.type === "AnimationFrame" /* AnimationFrame */ && !options.func)\n throw new Error("Callback must be provided to requestAnimationFrame calls");\n if (options.type === "IdleCallback" /* IdleCallback */ && !options.func)\n throw new Error("Callback must be provided to requestIdleCallback calls");\n if (["Timeout" /* Timeout */, "Interval" /* Interval */].includes(options.type) && !options.func && options.delay === void 0)\n throw new Error("Callback must be provided to timer calls");\n let delay = options.delay ? +options.delay : 0;\n if (!Number.isFinite(delay))\n delay = 0;\n delay = delay > maxTimeout ? 1 : delay;\n delay = Math.max(0, delay);\n const timer = {\n type: options.type,\n func: options.func,\n args: options.args || [],\n delay,\n callAt: shiftTicks(this._now.ticks, delay || (this._duringTick ? 1 : 0)),\n createdAt: this._now.ticks,\n id: this._uniqueTimerId++,\n error: new Error()\n };\n this._timers.set(timer.id, timer);\n if (this._realTime)\n this._updateRealTimeTimer();\n return timer.id;\n }\n countTimers() {\n return this._timers.size;\n }\n _firstTimer(beforeTick) {\n let firstTimer = null;\n for (const timer of this._timers.values()) {\n const isInRange = beforeTick === void 0 || timer.callAt <= beforeTick;\n if (isInRange && (!firstTimer || compareTimers(firstTimer, timer) === 1))\n firstTimer = timer;\n }\n return firstTimer;\n }\n _takeFirstTimer(beforeTick) {\n const timer = this._firstTimer(beforeTick);\n if (!timer)\n return null;\n this._advanceNow(timer.callAt);\n if (timer.type === "Interval" /* Interval */)\n timer.callAt = shiftTicks(timer.callAt, timer.delay);\n else\n this._timers.delete(timer.id);\n return timer;\n }\n async _callFirstTimer(beforeTick) {\n const timer = this._takeFirstTimer(beforeTick);\n if (!timer)\n return { timerFound: false };\n this._duringTick = true;\n try {\n if (typeof timer.func !== "function") {\n let error2;\n try {\n (() => {\n globalThis.eval(timer.func);\n })();\n } catch (e) {\n error2 = e;\n }\n await new Promise((f) => this._embedder.setTimeout(f));\n return { timerFound: true, error: error2 };\n }\n let args = timer.args;\n if (timer.type === "AnimationFrame" /* AnimationFrame */)\n args = [this._now.ticks];\n else if (timer.type === "IdleCallback" /* IdleCallback */)\n args = [{ didTimeout: false, timeRemaining: () => 0 }];\n let error;\n try {\n timer.func.apply(null, args);\n } catch (e) {\n error = e;\n }\n await new Promise((f) => this._embedder.setTimeout(f));\n return { timerFound: true, error };\n } finally {\n this._duringTick = false;\n }\n }\n getTimeToNextFrame() {\n this._replayLogOnce();\n return 16 - this._now.ticks % 16;\n }\n clearTimer(timerId, type) {\n this._replayLogOnce();\n if (!timerId) {\n return;\n }\n const id = Number(timerId);\n if (Number.isNaN(id) || id < idCounterStart) {\n const handlerName = getClearHandler(type);\n new Error(`Clock: ${handlerName} was invoked to clear a native timer instead of one created by the clock library.`);\n }\n const timer = this._timers.get(id);\n if (timer) {\n if (timer.type === type || timer.type === "Timeout" && type === "Interval" || timer.type === "Interval" && type === "Timeout") {\n this._timers.delete(id);\n } else {\n const clear = getClearHandler(type);\n const schedule = getScheduleHandler(timer.type);\n throw new Error(\n `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`\n );\n }\n }\n }\n _replayLogOnce() {\n if (!this._log.length)\n return;\n let lastLogTime = -1;\n let isPaused = false;\n for (const { type, time, param } of this._log) {\n if (!isPaused && lastLogTime !== -1)\n this._advanceNow(shiftTicks(this._now.ticks, time - lastLogTime));\n lastLogTime = time;\n if (type === "install") {\n this._innerInstall(asWallTime(param));\n } else if (type === "fastForward" || type === "runFor") {\n this._advanceNow(shiftTicks(this._now.ticks, param));\n } else if (type === "pauseAt") {\n isPaused = true;\n this._innerSetTime(asWallTime(param));\n } else if (type === "resume") {\n isPaused = false;\n } else if (type === "setFixedTime") {\n this._innerSetFixedTime(asWallTime(param));\n } else if (type === "setSystemTime") {\n this._innerSetTime(asWallTime(param));\n }\n }\n if (!isPaused) {\n if (lastLogTime > 0)\n this._advanceNow(shiftTicks(this._now.ticks, this._embedder.dateNow() - lastLogTime));\n this._innerResume();\n } else {\n this._realTime = void 0;\n }\n this._log.length = 0;\n }\n};\nfunction mirrorDateProperties(target, source) {\n for (const prop in source) {\n if (source.hasOwnProperty(prop))\n target[prop] = source[prop];\n }\n target.toString = () => source.toString();\n target.prototype = source.prototype;\n target.parse = source.parse;\n target.UTC = source.UTC;\n target.prototype.toUTCString = source.prototype.toUTCString;\n target.isFake = true;\n return target;\n}\nfunction createDate(clock, NativeDate) {\n function ClockDate(year, month, date, hour, minute, second, ms) {\n if (!(this instanceof ClockDate))\n return new NativeDate(clock.now()).toString();\n switch (arguments.length) {\n case 0:\n return new NativeDate(clock.now());\n case 1:\n return new NativeDate(year);\n case 2:\n return new NativeDate(year, month);\n case 3:\n return new NativeDate(year, month, date);\n case 4:\n return new NativeDate(year, month, date, hour);\n case 5:\n return new NativeDate(year, month, date, hour, minute);\n case 6:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second\n );\n default:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second,\n ms\n );\n }\n }\n ClockDate.now = () => clock.now();\n return mirrorDateProperties(ClockDate, NativeDate);\n}\nfunction createIntl(clock, NativeIntl) {\n const ClockIntl = {};\n for (const key of Object.getOwnPropertyNames(NativeIntl))\n ClockIntl[key] = NativeIntl[key];\n ClockIntl.DateTimeFormat = function(...args) {\n const realFormatter = new NativeIntl.DateTimeFormat(...args);\n const formatter = {\n formatRange: realFormatter.formatRange.bind(realFormatter),\n formatRangeToParts: realFormatter.formatRangeToParts.bind(realFormatter),\n resolvedOptions: realFormatter.resolvedOptions.bind(realFormatter),\n format: (date) => realFormatter.format(date || clock.now()),\n formatToParts: (date) => realFormatter.formatToParts(date || clock.now())\n };\n return formatter;\n };\n ClockIntl.DateTimeFormat.prototype = Object.create(\n NativeIntl.DateTimeFormat.prototype\n );\n ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf;\n return ClockIntl;\n}\nfunction createTemporal(clock, NativeTemporal) {\n const NativeNow = NativeTemporal.Now;\n const instant = () => NativeTemporal.Instant.fromEpochMilliseconds(Math.trunc(clock.now()));\n const zonedDateTimeISO = (timeZone) => instant().toZonedDateTimeISO(timeZone != null ? timeZone : NativeNow.timeZoneId());\n const overrides = {\n instant,\n zonedDateTimeISO,\n plainDateTimeISO: (timeZone) => zonedDateTimeISO(timeZone).toPlainDateTime(),\n plainDateISO: (timeZone) => zonedDateTimeISO(timeZone).toPlainDate(),\n plainTimeISO: (timeZone) => zonedDateTimeISO(timeZone).toPlainTime()\n };\n const ClockNow = Object.create(Object.getPrototypeOf(NativeNow), Object.getOwnPropertyDescriptors(NativeNow));\n for (const [key, value] of Object.entries(overrides))\n Object.defineProperty(ClockNow, key, { value, writable: true, enumerable: false, configurable: true });\n const ClockTemporal = Object.create(Object.getPrototypeOf(NativeTemporal), Object.getOwnPropertyDescriptors(NativeTemporal));\n Object.defineProperty(ClockTemporal, "Now", { value: ClockNow, writable: true, enumerable: false, configurable: true });\n return ClockTemporal;\n}\nfunction compareTimers(a, b) {\n if (a.callAt < b.callAt)\n return -1;\n if (a.callAt > b.callAt)\n return 1;\n if (a.type === "Immediate" /* Immediate */ && b.type !== "Immediate" /* Immediate */)\n return -1;\n if (a.type !== "Immediate" /* Immediate */ && b.type === "Immediate" /* Immediate */)\n return 1;\n if (a.createdAt < b.createdAt)\n return -1;\n if (a.createdAt > b.createdAt)\n return 1;\n if (a.id < b.id)\n return -1;\n if (a.id > b.id)\n return 1;\n}\nvar maxTimeout = Math.pow(2, 31) - 1;\nvar idCounterStart = 1e12;\nfunction platformOriginals(globalObject) {\n const raw = {\n setTimeout: globalObject.setTimeout,\n clearTimeout: globalObject.clearTimeout,\n setInterval: globalObject.setInterval,\n clearInterval: globalObject.clearInterval,\n requestAnimationFrame: globalObject.requestAnimationFrame ? globalObject.requestAnimationFrame : void 0,\n cancelAnimationFrame: globalObject.cancelAnimationFrame ? globalObject.cancelAnimationFrame : void 0,\n requestIdleCallback: globalObject.requestIdleCallback ? globalObject.requestIdleCallback : void 0,\n cancelIdleCallback: globalObject.cancelIdleCallback ? globalObject.cancelIdleCallback : void 0,\n Date: globalObject.Date,\n performance: globalObject.performance,\n Intl: globalObject.Intl,\n AbortSignal: globalObject.AbortSignal,\n Temporal: globalObject.Temporal\n };\n const bound = { ...raw };\n for (const key of Object.keys(bound)) {\n if (key !== "Date" && key !== "AbortSignal" && typeof bound[key] === "function")\n bound[key] = bound[key].bind(globalObject);\n }\n return { raw, bound };\n}\nfunction getScheduleHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `request${type}`;\n return `set${type}`;\n}\nfunction createApi(clock, originals, browserName) {\n return {\n setTimeout: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Timeout" /* Timeout */,\n func,\n args,\n delay\n });\n },\n clearTimeout: (timerId) => {\n if (timerId)\n clock.clearTimer(timerId, "Timeout" /* Timeout */);\n },\n setInterval: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Interval" /* Interval */,\n func,\n args,\n delay\n });\n },\n clearInterval: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "Interval" /* Interval */);\n },\n requestAnimationFrame: (callback) => {\n return clock.addTimer({\n type: "AnimationFrame" /* AnimationFrame */,\n func: callback,\n delay: clock.getTimeToNextFrame()\n });\n },\n cancelAnimationFrame: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "AnimationFrame" /* AnimationFrame */);\n },\n requestIdleCallback: (callback, options) => {\n let timeToNextIdlePeriod = 0;\n if (clock.countTimers() > 0)\n timeToNextIdlePeriod = 50;\n return clock.addTimer({\n type: "IdleCallback" /* IdleCallback */,\n func: callback,\n delay: (options == null ? void 0 : options.timeout) ? Math.min(options == null ? void 0 : options.timeout, timeToNextIdlePeriod) : timeToNextIdlePeriod\n });\n },\n cancelIdleCallback: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "IdleCallback" /* IdleCallback */);\n },\n Intl: originals.Intl ? createIntl(clock, originals.Intl) : void 0,\n Date: createDate(clock, originals.Date),\n performance: originals.performance ? fakePerformance(clock, originals.performance) : void 0,\n AbortSignal: originals.AbortSignal ? fakeAbortSignal(clock, originals.AbortSignal, browserName) : void 0,\n Temporal: originals.Temporal ? createTemporal(clock, originals.Temporal) : void 0\n };\n}\nfunction getClearHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `cancel${type}`;\n return `clear${type}`;\n}\nvar FakePerformanceEntry = class {\n constructor(name, entryType, startTime, duration) {\n this.name = name;\n this.entryType = entryType;\n this.startTime = startTime;\n this.duration = duration;\n }\n toJSON() {\n return JSON.stringify({ ...this });\n }\n};\nfunction fakePerformance(clock, performance) {\n const result = {\n now: () => clock.performanceNow()\n };\n result.__defineGetter__("timeOrigin", () => clock._now.origin || 0);\n for (const key of Object.keys(performance.__proto__)) {\n if (key === "now" || key === "timeOrigin")\n continue;\n if (key === "getEntries" || key === "getEntriesByName" || key === "getEntriesByType")\n result[key] = () => [];\n else if (key === "mark")\n result[key] = (name) => new FakePerformanceEntry(name, "mark", 0, 0);\n else if (key === "measure")\n result[key] = (name) => new FakePerformanceEntry(name, "measure", 0, 50);\n else\n result[key] = () => {\n };\n }\n return result;\n}\nfunction fakeAbortSignal(clock, abortSignal, browserName) {\n Object.defineProperty(abortSignal, "timeout", {\n value(ms) {\n const controller = new AbortController();\n clock.addTimer({\n delay: ms,\n type: "Timeout" /* Timeout */,\n func: () => controller.abort(\n new DOMException(\n browserName === "chromium" ? "signal timed out" : "The operation timed out.",\n "TimeoutError"\n )\n )\n });\n return controller.signal;\n }\n });\n return abortSignal;\n}\nfunction createClock(globalObject, config = {}) {\n const originals = platformOriginals(globalObject);\n const embedder = {\n dateNow: () => originals.raw.Date.now(),\n performanceNow: () => Math.ceil(originals.raw.performance.now()),\n setTimeout: (task, timeout) => {\n const timerId = originals.bound.setTimeout(task, timeout);\n return () => originals.bound.clearTimeout(timerId);\n },\n setInterval: (task, delay) => {\n const intervalId = originals.bound.setInterval(task, delay);\n return () => originals.bound.clearInterval(intervalId);\n }\n };\n const clock = new ClockController(embedder);\n const api = createApi(clock, originals.bound, config.browserName);\n return { clock, api, originals: originals.raw };\n}\nfunction install(globalObject, config = {}) {\n var _a, _b;\n if ((_a = globalObject.Date) == null ? void 0 : _a.isFake) {\n throw new TypeError(`Can\'t install fake timers twice on the same global object.`);\n }\n const { clock, api, originals } = createClock(globalObject, config);\n const toFake = ((_b = config.toFake) == null ? void 0 : _b.length) ? config.toFake : Object.keys(originals);\n for (const method of toFake) {\n if (method === "Temporal" && !api.Temporal)\n continue;\n if (method === "Date") {\n globalObject.Date = mirrorDateProperties(api.Date, globalObject.Date);\n } else if (method === "Intl") {\n globalObject.Intl = api[method];\n } else if (method === "AbortSignal") {\n globalObject.AbortSignal = api[method];\n } else if (method === "Temporal") {\n globalObject.Temporal = api[method];\n } else if (method === "performance") {\n globalObject.performance = api[method];\n const kEventTimeStamp = /* @__PURE__ */ Symbol("playwrightEventTimeStamp");\n Object.defineProperty(Event.prototype, "timeStamp", {\n get() {\n var _a2;\n if (!this[kEventTimeStamp])\n this[kEventTimeStamp] = (_a2 = api.performance) == null ? void 0 : _a2.now();\n return this[kEventTimeStamp];\n }\n });\n } else {\n globalObject[method] = (...args) => {\n return api[method].apply(api, args);\n };\n }\n clock.disposables.push(() => {\n globalObject[method] = originals[method];\n });\n }\n return { clock, api, originals };\n}\nfunction inject(globalObject, browserName) {\n const builtins = platformOriginals(globalObject).bound;\n const { clock: controller } = install(globalObject, { browserName });\n controller.resume();\n return {\n controller,\n builtins\n };\n}\nfunction asWallTime(n) {\n return n;\n}\nfunction shiftTicks(ticks, ms) {\n return ticks + ms;\n}\n'; + } +}); + +// packages/protocol/src/serializers.ts +function systemErrorCode(error) { + return typeof error.code === "string" ? error.code : void 0; +} +function systemErrorMessage(error) { + const message = error.message; + if (typeof error.code !== "string" || !/^E[A-Z0-9]+$/.test(error.code) || message.includes(error.code)) + return message; + return `${message} (${error.code})`; +} +function parseSerializedValue(value2, handles) { + return innerParseSerializedValue(value2, handles, /* @__PURE__ */ new Map(), []); +} +function innerParseSerializedValue(value2, handles, refs, accessChain) { + if (value2.ref !== void 0) + return refs.get(value2.ref); + if (value2.n !== void 0) + return value2.n; + if (value2.s !== void 0) + return value2.s; + if (value2.b !== void 0) + return value2.b; + if (value2.v !== void 0) { + if (value2.v === "undefined") + return void 0; + if (value2.v === "null") + return null; + if (value2.v === "NaN") + return NaN; + if (value2.v === "Infinity") + return Infinity; + if (value2.v === "-Infinity") + return -Infinity; + if (value2.v === "-0") + return -0; + } + if (value2.d !== void 0) + return new Date(value2.d); + if (value2.u !== void 0) + return new URL(value2.u); + if (value2.bi !== void 0) + return BigInt(value2.bi); + if (value2.e !== void 0) { + const error = new Error(value2.e.m); + error.name = value2.e.n; + error.stack = value2.e.s; + return error; + } + if (value2.r !== void 0) + return new RegExp(value2.r.p, value2.r.f); + if (value2.ta !== void 0) { + const ctor = typedArrayKindToConstructor[value2.ta.k]; + return new ctor(value2.ta.b.buffer, value2.ta.b.byteOffset, value2.ta.b.length / ctor.BYTES_PER_ELEMENT); + } + if (value2.a !== void 0) { + const result2 = []; + refs.set(value2.id, result2); + for (let i = 0; i < value2.a.length; i++) + result2.push(innerParseSerializedValue(value2.a[i], handles, refs, [...accessChain, i])); + return result2; + } + if (value2.o !== void 0) { + const result2 = {}; + refs.set(value2.id, result2); + for (const { k, v } of value2.o) + result2[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]); + return result2; + } + if (value2.h !== void 0) { + if (handles === void 0) + throw new Error("Unexpected handle"); + return handles[value2.h]; + } + if (value2.fn !== void 0) { + const dummy = () => { + }; + Object.defineProperty(dummy, "name", { value: value2.fn }); + return dummy; + } + throw new Error(`Attempting to deserialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`); +} +function serializeValue(value2, handleSerializer) { + return innerSerializeValue(value2, handleSerializer, { lastId: 0, visited: /* @__PURE__ */ new Map() }, []); +} +function innerSerializeValue(value2, handleSerializer, visitorInfo, accessChain) { + const handle = handleSerializer(value2); + if ("fallThrough" in handle) + value2 = handle.fallThrough; + else + return handle; + if (typeof value2 === "symbol") + return { v: "undefined" }; + if (Object.is(value2, void 0)) + return { v: "undefined" }; + if (Object.is(value2, null)) + return { v: "null" }; + if (Object.is(value2, NaN)) + return { v: "NaN" }; + if (Object.is(value2, Infinity)) + return { v: "Infinity" }; + if (Object.is(value2, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value2, -0)) + return { v: "-0" }; + if (typeof value2 === "boolean") + return { b: value2 }; + if (typeof value2 === "number") + return { n: value2 }; + if (typeof value2 === "string") + return { s: value2 }; + if (typeof value2 === "bigint") + return { bi: value2.toString() }; + if (isError2(value2)) + return { e: { n: value2.name, m: value2.message, s: value2.stack || "" } }; + if (isDate(value2)) + return { d: value2.toJSON() }; + if (isURL(value2)) + return { u: value2.toJSON() }; + if (isRegExp4(value2)) + return { r: { p: value2.source, f: value2.flags } }; + const typedArrayKind = constructorToTypedArrayKind.get(value2.constructor); + if (typedArrayKind) + return { ta: { b: Buffer.from(value2.buffer, value2.byteOffset, value2.byteLength), k: typedArrayKind } }; + const id = visitorInfo.visited.get(value2); + if (id) + return { ref: id }; + if (Array.isArray(value2)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (let i = 0; i < value2.length; ++i) + a.push(innerSerializeValue(value2[i], handleSerializer, visitorInfo, [...accessChain, i])); + return { a, id: id2 }; + } + if (typeof value2 === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (const name of Object.keys(value2)) + o.push({ k: name, v: innerSerializeValue(value2[name], handleSerializer, visitorInfo, [...accessChain, name]) }); + return { o, id: id2 }; + } + throw new Error(`Attempting to serialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`); +} +function accessChainToDisplayString(accessChain) { + const chainString = accessChain.map((accessor, i) => { + if (typeof accessor === "string") + return i ? `.${accessor}` : accessor; + return `[${accessor}]`; + }).join(""); + return chainString.length > 0 ? ` at position "${chainString}"` : ""; +} +function isRegExp4(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function isDate(obj) { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; +} +function isURL(obj) { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; +} +function isError2(obj) { + const proto = obj ? Object.getPrototypeOf(obj) : null; + return obj instanceof Error || proto?.name === "Error" || proto && isError2(proto); +} +var typedArrayKindToConstructor, constructorToTypedArrayKind; +var init_serializers = __esm({ + "packages/protocol/src/serializers.ts"() { + "use strict"; + typedArrayKindToConstructor = { + i8: Int8Array, + ui8: Uint8Array, + ui8c: Uint8ClampedArray, + i16: Int16Array, + ui16: Uint16Array, + i32: Int32Array, + ui32: Uint32Array, + f32: Float32Array, + f64: Float64Array, + bi64: BigInt64Array, + bui64: BigUint64Array + }; + constructorToTypedArrayKind = new Map(Object.entries(typedArrayKindToConstructor).map(([k, v]) => [v, k])); + } +}); + +// packages/playwright-core/src/server/protocolError.ts +function isProtocolError(e) { + return e instanceof ProtocolError; +} +function isSessionClosedError(e) { + return e instanceof ProtocolError && (e.type === "closed" || e.type === "crashed"); +} +var ProtocolError; +var init_protocolError = __esm({ + "packages/playwright-core/src/server/protocolError.ts"() { + "use strict"; + init_stackTrace(); + ProtocolError = class extends Error { + constructor(type3, method2, logs) { + super(); + this.type = type3; + this.method = method2; + this.logs = logs; + } + setMessage(message) { + rewriteErrorMessage(this, `Protocol error (${this.method}): ${message}`); + } + browserLogMessage() { + return this.logs ? "\nBrowser logs:\n" + this.logs : ""; + } + }; + } +}); + +// packages/playwright-core/src/server/errors.ts +function isTargetClosedError(error) { + return error instanceof TargetClosedError || error.name === "TargetClosedError"; +} +function rewriteErrorForClosedTarget(error, closeReason) { + if (isTargetClosedError(error)) { + if (closeReason) + rewriteErrorMessage(error, closeReason); + } else if (isProtocolError(error)) { + if (error.type === "closed") + return new TargetClosedError(closeReason, error.browserLogMessage()); + if (error.type === "crashed") + rewriteErrorMessage(error, "Target crashed " + error.browserLogMessage()); + } + return error; +} +function serializeError(e) { + if (isError(e)) + return { error: { message: systemErrorMessage(e), stack: e.stack, name: e.name, code: systemErrorCode(e) } }; + return { value: serializeValue(e, (value2) => ({ fallThrough: value2 })) }; +} +function parseError(error) { + if (!error.error) { + if (error.value === void 0) + throw new Error("Serialized error must have either an error or a value"); + return parseSerializedValue(error.value, void 0); + } + const e = new Error(error.error.message); + e.stack = error.error.stack || ""; + e.name = error.error.name; + if (error.error.code !== void 0) + e.code = error.error.code; + return e; +} +var CustomError, TimeoutError, EvaluationStalledError, TargetClosedError, AbortError; +var init_errors = __esm({ + "packages/playwright-core/src/server/errors.ts"() { + "use strict"; + init_rtti(); + init_serializers(); + init_stackTrace(); + init_protocolError(); + CustomError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = this.constructor.name; + } + }; + TimeoutError = class extends CustomError { + }; + EvaluationStalledError = class extends CustomError { + }; + TargetClosedError = class extends CustomError { + constructor(cause, logs) { + super((cause || "Target page, context or browser has been closed") + (logs || "")); + } + }; + AbortError = class extends CustomError { + constructor(message = "The operation was aborted", options) { + super(message, options); + this.name = "AbortError"; + } + }; + } +}); + +// packages/playwright-core/src/server/progress.ts +function isAbortError(error) { + return error instanceof TimeoutError || !!error[kAbortErrorSymbol]; +} +async function raceUncancellableOperationWithCleanup(progress2, run, cleanup) { + let aborted = false; + try { + return await progress2.race(run().then(async (t) => { + if (aborted) + await cleanup(t); + return t; + })); + } catch (error) { + aborted = true; + throw error; + } +} +var ProgressController, kAbortErrorSymbol, nullProgress; +var init_progress = __esm({ + "packages/playwright-core/src/server/progress.ts"() { + "use strict"; + init_manualPromise(); + init_assert(); + init_time(); + init_debugLogger(); + init_errors(); + ProgressController = class _ProgressController { + constructor(metadata, onCallLog, pendingAbortError) { + this._forceAbortPromise = new ManualPromise(); + this._donePromise = new ManualPromise(); + this._state = "before"; + this.metadata = metadata || { id: "", startTime: 0, endTime: 0, type: "Internal", method: "", params: {}, log: [], internal: true }; + this._onCallLog = onCallLog; + this._pendingAbortError = pendingAbortError; + this._forceAbortPromise.catch((e) => null); + this._controller = new AbortController(); + } + static createForSdkObject(sdkObject, callMetadata, pendingAbortError) { + const logName = sdkObject.logName || "api"; + return new _ProgressController(callMetadata, (message) => { + if (logName === "api" && sdkObject.attribution.playwright?.options.isInternalPlaywright) + return; + debugLogger.log(logName, message); + sdkObject.instrumentation.onCallLog(sdkObject, callMetadata, logName, message); + }, pendingAbortError); + } + async abort(error) { + const logMessage = `operation was aborted: ${error.message}`; + if (this._state === "running") { + this.metadata.log.push(logMessage); + error[kAbortErrorSymbol] = true; + this._state = { error }; + this._forceAbortPromise.reject(error); + this._controller.abort(error); + } else if (this._state === "before") { + this.metadata.log.push(logMessage); + error[kAbortErrorSymbol] = true; + this._pendingAbortError = error; + } + await this._donePromise; + } + async run(task, timeout) { + const deadline = timeout ? monotonicTime() + timeout : 0; + assert(this._state === "before"); + this._state = "running"; + let timer; + let outerProgress; + let allowConcurrent = false; + const progress2 = { + timeout: timeout ?? 0, + deadline, + disableTimeout: () => { + clearTimeout(timer); + }, + log: (message) => { + if (this._state === "running") + this.metadata.log.push(message); + this._onCallLog?.(message); + }, + metadata: this.metadata, + setAllowConcurrentOrNestedRaces: (allow) => { + allowConcurrent = allow; + }, + race: (promise) => { + if (process.env.PW_DETECT_NESTED_PROGRESS) { + const innerProgress = new Error().stack; + if (outerProgress && !allowConcurrent && outerProgress !== innerProgress) { + console.error("Cannot call race() inside another race()"); + console.error("<<<<>>>>:", outerProgress); + console.error("<<<<>>>>:", innerProgress); + } + outerProgress = innerProgress; + } + const promises2 = Array.isArray(promise) ? promise : [promise]; + if (!promises2.length) + return Promise.resolve(); + return Promise.race([...promises2, this._forceAbortPromise]).finally(() => outerProgress = void 0); + }, + wait: async (timeout2) => { + let timer2; + const promise = new Promise((f) => timer2 = setTimeout(f, timeout2)); + return progress2.race(promise).finally(() => clearTimeout(timer2)); + }, + signal: this._controller.signal + }; + if (deadline) { + const timeoutError = new TimeoutError(`Timeout ${timeout}ms exceeded.`); + timer = setTimeout(() => { + if (this.metadata.pauseStartTime && !this.metadata.pauseEndTime) + return; + if (this._state === "running") { + this._state = { error: timeoutError }; + this._forceAbortPromise.reject(timeoutError); + this._controller.abort(timeoutError); + } + }, deadline - monotonicTime()); + } + try { + if (this._pendingAbortError) + throw this._pendingAbortError; + const result2 = await task(progress2); + this._state = "finished"; + return result2; + } catch (error) { + this._state = { error }; + throw error; + } finally { + clearTimeout(timer); + this._donePromise.resolve(); + } + } + }; + kAbortErrorSymbol = /* @__PURE__ */ Symbol("kAbortError"); + nullProgress = { + timeout: 0, + deadline: 0, + disableTimeout() { + }, + log() { + }, + race(promise) { + const promises2 = Array.isArray(promise) ? promise : [promise]; + return Promise.race(promises2); + }, + wait: async (timeout) => await new Promise((f) => setTimeout(f, timeout)), + signal: new AbortController().signal, + metadata: { + id: "", + startTime: 0, + endTime: 0, + type: "", + method: "", + params: {}, + log: [], + internal: true + }, + setAllowConcurrentOrNestedRaces() { + } + }; + } +}); + +// packages/playwright-core/src/server/clock.ts +function parseTicks(value2) { + if (typeof value2 === "number") + return value2; + if (!value2) + return 0; + const str = value2; + const strings = str.split(":"); + const l = strings.length; + let i = l; + let ms = 0; + let parsed; + if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { + throw new Error( + `Clock only understands numbers, 'mm:ss' and 'hh:mm:ss'` + ); + } + while (i--) { + parsed = parseInt(strings[i], 10); + if (parsed >= 60) + throw new Error(`Invalid time ${str}`); + ms += parsed * Math.pow(60, l - i - 1); + } + return ms * 1e3; +} +function parseTime(epoch) { + if (!epoch) + return 0; + const parsed = new Date(epoch); + if (!isFinite(parsed.getTime())) + throw new Error(`Invalid date: ${epoch}`); + return typeof epoch === "number" ? epoch : parsed.getTime(); +} +var Clock; +var init_clock = __esm({ + "packages/playwright-core/src/server/clock.ts"() { + "use strict"; + init_clockSource(); + init_progress(); + Clock = class { + constructor(browserContext) { + this._initScripts = []; + this._browserContext = browserContext; + } + async uninstall(progress2) { + await progress2.race(Promise.all(this._initScripts.map((script) => script.dispose()))); + this._initScripts = []; + } + async fastForward(ticks) { + await this._installIfNeeded(); + const ticksMillis = parseTicks(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('fastForward', ${Date.now()}, ${ticksMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.fastForward(${ticksMillis})`); + } + async install(time) { + await this._installIfNeeded(); + const timeMillis = time !== void 0 ? parseTime(time) : Date.now(); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('install', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.install(${timeMillis})`); + } + async pauseAt(ticks) { + await this._installIfNeeded(); + const timeMillis = parseTime(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('pauseAt', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.pauseAt(${timeMillis})`); + } + resumeNoReply() { + if (!this._initScripts.length) + return; + const doResume = async () => { + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`); + }; + doResume().catch(() => { + }); + } + async resume(progress2) { + await progress2.race(this._installIfNeeded()); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`)); + await progress2.race(this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`)); + } + async setFixedTime(time) { + await this._installIfNeeded(); + const timeMillis = parseTime(time); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setFixedTime', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.setFixedTime(${timeMillis})`); + } + async setSystemTime(time) { + await this._installIfNeeded(); + const timeMillis = parseTime(time); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setSystemTime', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.setSystemTime(${timeMillis})`); + } + async runFor(ticks) { + await this._installIfNeeded(); + const ticksMillis = parseTicks(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('runFor', ${Date.now()}, ${ticksMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.runFor(${ticksMillis})`); + } + async _installIfNeeded() { + if (this._initScripts.length) + return; + const script = `(() => { + const module = {}; + ${source} + if (!globalThis.__pwClock) + globalThis.__pwClock = (module.exports.inject())(globalThis, ${JSON.stringify(this._browserContext._browser.options.name)}); + })();`; + const initScript = await this._browserContext.addInitScript(nullProgress, script); + await this._evaluateInFrames(script); + this._initScripts.push(initScript); + } + async _evaluateInFrames(script) { + await this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: true }); + } + }; + } +}); + +// packages/playwright-core/src/generated/webAuthnSource.ts +var source2; +var init_webAuthnSource = __esm({ + "packages/playwright-core/src/generated/webAuthnSource.ts"() { + "use strict"; + source2 = ` +var __commonJS = obj => { + let required = false; + let result; + return function __require() { + if (!required) { + required = true; + let fn; + for (const name in obj) { fn = obj[name]; break; } + const module = { exports: {} }; + fn(module.exports, module); + result = module.exports; + } + return result; + } +}; +var __export = (target, all) => {for (var name in all) target[name] = all[name];}; +var __toESM = mod => ({ ...mod, 'default': mod }); +var __toCommonJS = mod => ({ ...mod, __esModule: true }); + + +// packages/injected/src/webAuthn.ts +var webAuthn_exports = {}; +__export(webAuthn_exports, { + inject: () => inject +}); +module.exports = __toCommonJS(webAuthn_exports); +function inject(globalThis) { + if (globalThis.__pwWebAuthnInstalled) + return; + globalThis.__pwWebAuthnInstalled = true; + const binding = globalThis.__pwWebAuthnBinding; + if (!binding || !globalThis.navigator) + return; + if (!globalThis.navigator.credentials) { + Object.defineProperty(globalThis.navigator, "credentials", { + value: { create: async () => null, get: async () => null }, + writable: true, + configurable: true + }); + } + function toBase64Url(buf) { + const bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + let s = ""; + for (let i = 0; i < bytes.length; i++) + s += String.fromCharCode(bytes[i]); + return globalThis.btoa(s).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); + } + function fromBase64Url(s) { + let str = s.replaceAll("-", "+").replaceAll("_", "/"); + while (str.length % 4) + str += "="; + const bin = globalThis.atob(str); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) + out[i] = bin.charCodeAt(i); + return out.buffer; + } + const PublicKeyCredentialCtor = globalThis.PublicKeyCredential; + const AuthAttestationResponseCtor = globalThis.AuthenticatorAttestationResponse; + const AuthAssertionResponseCtor = globalThis.AuthenticatorAssertionResponse; + function defineReadonly(target, props) { + for (const k of Object.keys(props)) + Object.defineProperty(target, k, { value: props[k], enumerable: true, configurable: true }); + } + function makeAttestationResponse(clientDataJSON, attestationObject, authenticatorData, publicKey) { + const proto = (AuthAttestationResponseCtor == null ? void 0 : AuthAttestationResponseCtor.prototype) || Object.prototype; + const r = Object.create(proto); + defineReadonly(r, { clientDataJSON, attestationObject }); + r.getTransports = () => ["internal"]; + r.getAuthenticatorData = () => authenticatorData; + r.getPublicKey = () => publicKey; + r.getPublicKeyAlgorithm = () => -7; + return r; + } + function makeAssertionResponse(clientDataJSON, authenticatorData, signature, userHandle) { + const proto = (AuthAssertionResponseCtor == null ? void 0 : AuthAssertionResponseCtor.prototype) || Object.prototype; + const r = Object.create(proto); + defineReadonly(r, { clientDataJSON, authenticatorData, signature, userHandle }); + return r; + } + function makePublicKeyCredential(id, response, responseToJSON) { + const proto = (PublicKeyCredentialCtor == null ? void 0 : PublicKeyCredentialCtor.prototype) || Object.prototype; + const cred = Object.create(proto); + defineReadonly(cred, { + id, + rawId: fromBase64Url(id), + type: "public-key", + authenticatorAttachment: "platform", + response + }); + cred.getClientExtensionResults = () => ({}); + cred.toJSON = () => ({ + id, + rawId: id, + response: responseToJSON(), + authenticatorAttachment: "platform", + clientExtensionResults: {}, + type: "public-key" + }); + return cred; + } + function toBuf(x) { + if (!x) + return new ArrayBuffer(0); + if (x instanceof ArrayBuffer) + return x; + const v = x; + const out = new Uint8Array(v.byteLength); + out.set(new Uint8Array(v.buffer, v.byteOffset, v.byteLength)); + return out.buffer; + } + function failure(name, message) { + const Ctor = globalThis.DOMException || Error; + throw new Ctor(message, name); + } + const origCreate = globalThis.navigator.credentials.create.bind(globalThis.navigator.credentials); + const origGet = globalThis.navigator.credentials.get.bind(globalThis.navigator.credentials); + globalThis.navigator.credentials.create = async function(options) { + var _a, _b, _c, _d, _e, _f, _g; + if (!options || !options.publicKey) + return origCreate(options); + const pk = options.publicKey; + const req = { + type: "create", + origin: globalThis.location.origin, + challenge: toBase64Url(toBuf(pk.challenge)), + rp: { id: (_a = pk.rp) == null ? void 0 : _a.id, name: ((_b = pk.rp) == null ? void 0 : _b.name) || "" }, + user: { + id: toBase64Url(toBuf((_c = pk.user) == null ? void 0 : _c.id)), + name: ((_d = pk.user) == null ? void 0 : _d.name) || "", + displayName: ((_e = pk.user) == null ? void 0 : _e.displayName) || "" + }, + pubKeyCredParams: (pk.pubKeyCredParams || []).map((p) => ({ type: p.type, alg: p.alg })), + excludeCredentials: (pk.excludeCredentials || []).map((c) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })), + userVerification: (_f = pk.authenticatorSelection) == null ? void 0 : _f.userVerification, + residentKey: (_g = pk.authenticatorSelection) == null ? void 0 : _g.residentKey + }; + const result = await binding(req); + if (!result.ok) + failure(result.name, result.message); + const resp = makeAttestationResponse( + fromBase64Url(result.clientDataJSON), + fromBase64Url(result.attestationObject), + fromBase64Url(result.authenticatorData), + fromBase64Url(result.publicKey) + ); + return makePublicKeyCredential(result.id, resp, () => ({ + clientDataJSON: result.clientDataJSON, + authenticatorData: result.authenticatorData, + transports: resp.getTransports(), + publicKey: result.publicKey, + publicKeyAlgorithm: resp.getPublicKeyAlgorithm(), + attestationObject: result.attestationObject + })); + }; + globalThis.navigator.credentials.get = async function(options) { + if (!options || !options.publicKey) + return origGet(options); + const pk = options.publicKey; + const req = { + type: "get", + origin: globalThis.location.origin, + challenge: toBase64Url(toBuf(pk.challenge)), + rpId: pk.rpId || new URL(globalThis.location.origin).hostname, + allowCredentials: (pk.allowCredentials || []).map((c) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })), + userVerification: pk.userVerification + }; + const result = await binding(req); + if (!result.ok) + failure(result.name, result.message); + const resp = makeAssertionResponse( + fromBase64Url(result.clientDataJSON), + fromBase64Url(result.authenticatorData), + fromBase64Url(result.signature), + result.userHandle ? fromBase64Url(result.userHandle) : null + ); + return makePublicKeyCredential(result.id, resp, () => ({ + clientDataJSON: result.clientDataJSON, + authenticatorData: result.authenticatorData, + signature: result.signature, + ...result.userHandle ? { userHandle: result.userHandle } : {} + })); + }; + if (PublicKeyCredentialCtor) { + PublicKeyCredentialCtor.isUserVerifyingPlatformAuthenticatorAvailable = async () => true; + PublicKeyCredentialCtor.isConditionalMediationAvailable = async () => true; + } +} +`; + } +}); + +// packages/playwright-core/src/server/credentials.ts +function toPublic(r) { + return { id: r.id, rpId: r.rpId, userHandle: r.userHandle, privateKey: r.privateKey, publicKey: r.publicKey, signCount: r.signCount }; +} +function randomBase64Url(bytes) { + return bufToB64Url(import_crypto5.default.randomBytes(bytes)); +} +function bufToB64Url(b) { + return b.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +} +function b64UrlToBuf(s) { + return Buffer.from(s, "base64url"); +} +function u32ToBytes(n) { + const b = Buffer.alloc(4); + b.writeUInt32BE(n >>> 0, 0); + return b; +} +function cborHead(major, value2) { + const m = major << 5; + if (value2 < 24) + return Buffer.from([m | value2]); + if (value2 < 256) + return Buffer.from([m | 24, value2]); + if (value2 < 65536) + return Buffer.from([m | 25, value2 >> 8 & 255, value2 & 255]); + return Buffer.from([m | 26, value2 >>> 24 & 255, value2 >> 16 & 255, value2 >> 8 & 255, value2 & 255]); +} +function cborUint(v) { + return cborHead(0, v); +} +function cborNint(v) { + return cborHead(1, -1 - v); +} +function cborBytes(b) { + return Buffer.concat([cborHead(2, b.length), b]); +} +function cborText(s) { + const b = Buffer.from(s, "utf8"); + return Buffer.concat([cborHead(3, b.length), b]); +} +function cborMap(entries) { + return Buffer.concat([cborHead(5, entries.length), ...entries.flatMap(([k, v]) => [k, v])]); +} +function encodeCoseEs256PublicKey(publicKey) { + const jwk = publicKey.export({ format: "jwk" }); + const x = Buffer.from(jwk.x, "base64url"); + const y = Buffer.from(jwk.y, "base64url"); + return cborMap([ + [cborUint(1), cborUint(2)], + // kty = EC2 + [cborUint(3), cborNint(-7)], + // alg = ES256 + [cborNint(-1), cborUint(1)], + // crv = P-256 + [cborNint(-2), cborBytes(x)], + [cborNint(-3), cborBytes(y)] + ]); +} +function encodeAttestationObjectNone(authData) { + return cborMap([ + [cborText("fmt"), cborText("none")], + [cborText("attStmt"), cborMap([])], + [cborText("authData"), cborBytes(authData)] + ]); +} +var import_crypto5, kBindingName, kAuthenticatorAAGUID, Credentials; +var init_credentials = __esm({ + "packages/playwright-core/src/server/credentials.ts"() { + "use strict"; + import_crypto5 = __toESM(require("crypto")); + init_webAuthnSource(); + init_progress(); + kBindingName = "__pwWebAuthnBinding"; + kAuthenticatorAAGUID = Buffer.alloc(16); + Credentials = class { + constructor(browserContext) { + this._registry = /* @__PURE__ */ new Map(); + this._browserContext = browserContext; + } + async create(options) { + const signCount = options.signCount ?? 0; + if (signCount < 0 || signCount > 4294967295) + throw new Error(`signCount must be between 0 and 4294967295, got ${signCount}`); + let privateKey = options.privateKey; + let publicKey = options.publicKey; + if (!privateKey || !publicKey) { + const pair = import_crypto5.default.generateKeyPairSync("ec", { namedCurve: "P-256" }); + privateKey = bufToB64Url(pair.privateKey.export({ format: "der", type: "pkcs8" })); + publicKey = bufToB64Url(pair.publicKey.export({ format: "der", type: "spki" })); + } + const record = { + id: options.id || randomBase64Url(16), + rpId: options.rpId, + userHandle: options.userHandle || randomBase64Url(16), + privateKey, + publicKey, + signCount, + isResident: true + }; + this._registry.set(record.id, record); + return toPublic(record); + } + async get(filter2) { + return [...this._registry.values()].filter((c) => { + if (filter2?.rpId && c.rpId !== filter2.rpId) + return false; + if (filter2?.id && c.id !== filter2.id) + return false; + return true; + }).map(toPublic); + } + async delete(id) { + this._registry.delete(id); + } + clear() { + this._registry.clear(); + } + async dispose(progress2) { + if (this._initScript) { + await progress2.race(this._initScript.dispose()); + this._initScript = void 0; + } + if (this._binding) { + await progress2.race(this._binding.dispose()); + this._binding = void 0; + } + this._registry.clear(); + } + async install(progress2) { + if (this._binding) + return; + this._binding = await this._browserContext.exposeBinding(progress2, kBindingName, async (_source, payload) => { + try { + if (payload?.type === "create") + return await this._handleCreate(payload); + if (payload?.type === "get") + return this._handleGet(payload); + } catch (e) { + return { ok: false, name: "NotAllowedError", message: e.message }; + } + return { ok: false, name: "NotAllowedError", message: "Unknown WebAuthn request" }; + }); + const script = `(() => { + const module = {}; + ${source2} + module.exports.inject()(globalThis); + })();`; + this._initScript = await this._browserContext.addInitScript(nullProgress, script); + await progress2.race(this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: false })); + } + async _handleCreate(req) { + const rpId = req.rp?.id || new URL(req.origin).hostname; + const userHandle = req.user.id; + if (req.excludeCredentials?.length) { + for (const desc of req.excludeCredentials) { + if (this._registry.has(desc.id)) + return { ok: false, name: "InvalidStateError", message: "Credential excluded" }; + } + } + const pair = import_crypto5.default.generateKeyPairSync("ec", { namedCurve: "P-256" }); + const privateKey = bufToB64Url(pair.privateKey.export({ format: "der", type: "pkcs8" })); + const publicKey = bufToB64Url(pair.publicKey.export({ format: "der", type: "spki" })); + const credentialId = import_crypto5.default.randomBytes(16); + const credentialIdB64 = bufToB64Url(credentialId); + const record = { + id: credentialIdB64, + rpId, + userHandle, + privateKey, + publicKey, + signCount: 0, + isResident: req.residentKey === "required" || req.residentKey === "preferred" + }; + this._registry.set(credentialIdB64, record); + const clientDataJSON = Buffer.from(JSON.stringify({ + type: "webauthn.create", + challenge: req.challenge, + origin: req.origin, + crossOrigin: false + })); + const rpIdHash = import_crypto5.default.createHash("sha256").update(rpId).digest(); + const flags = 1 | 4 | 64; + const signCountBuf = u32ToBytes(record.signCount); + const cosePublicKey = encodeCoseEs256PublicKey(pair.publicKey); + const credIdLenBuf = Buffer.from([credentialId.length >> 8 & 255, credentialId.length & 255]); + const attestedCredentialData = Buffer.concat([kAuthenticatorAAGUID, credIdLenBuf, credentialId, cosePublicKey]); + const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf, attestedCredentialData]); + const attestationObject = encodeAttestationObjectNone(authData); + return { + ok: true, + id: credentialIdB64, + clientDataJSON: bufToB64Url(clientDataJSON), + attestationObject: bufToB64Url(attestationObject), + authenticatorData: bufToB64Url(authData), + publicKey + }; + } + _handleGet(req) { + const rpId = req.rpId || new URL(req.origin).hostname; + let candidate; + if (req.allowCredentials?.length) { + for (const desc of req.allowCredentials) { + const c = this._registry.get(desc.id); + if (c && c.rpId === rpId) { + candidate = c; + break; + } + } + } else { + for (const c of this._registry.values()) { + if (c.rpId === rpId && c.isResident) { + candidate = c; + break; + } + } + } + if (!candidate) + return { ok: false, name: "NotAllowedError", message: "No matching credential" }; + const clientDataJSON = Buffer.from(JSON.stringify({ + type: "webauthn.get", + challenge: req.challenge, + origin: req.origin, + crossOrigin: false + })); + const rpIdHash = import_crypto5.default.createHash("sha256").update(rpId).digest(); + const flags = 1 | 4; + candidate.signCount += 1; + const signCountBuf = u32ToBytes(candidate.signCount); + const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf]); + const clientDataHash = import_crypto5.default.createHash("sha256").update(clientDataJSON).digest(); + const toSign = Buffer.concat([authData, clientDataHash]); + const privateKey = import_crypto5.default.createPrivateKey({ key: b64UrlToBuf(candidate.privateKey), format: "der", type: "pkcs8" }); + const signature = import_crypto5.default.sign("sha256", toSign, privateKey); + return { + ok: true, + id: candidate.id, + clientDataJSON: bufToB64Url(clientDataJSON), + authenticatorData: bufToB64Url(authData), + signature: bufToB64Url(signature), + userHandle: candidate.userHandle || null + }; + } + }; + } +}); + +// packages/playwright-core/src/server/instrumentation.ts +function createRootSdkObject() { + const fakeParent = { attribution: {}, instrumentation: createInstrumentation() }; + const root = new SdkObject(fakeParent); + root.guid = ""; + return root; +} +function createInstrumentation() { + const listeners = /* @__PURE__ */ new Map(); + const lastListeners = /* @__PURE__ */ new Map(); + return new Proxy({}, { + get: (obj, prop) => { + if (typeof prop !== "string") + return obj[prop]; + if (prop === "addListener") { + return (listener, context, options) => { + if (options?.order === "last") + lastListeners.set(listener, context); + else + listeners.set(listener, context); + }; + } + if (prop === "removeListener") { + return (listener) => { + listeners.delete(listener); + lastListeners.delete(listener); + }; + } + if (!prop.startsWith("on")) + return obj[prop]; + return async (...params2) => { + const sdkObject = params2[0] instanceof SdkObject ? params2[0] : params2[1]; + for (const [listener, context] of listeners) { + if (!context || sdkObject.attribution.context === context) + await listener[prop]?.(...params2); + } + for (const [listener, context] of lastListeners) { + if (!context || sdkObject.attribution.context === context) + await listener[prop]?.(...params2); + } + }; + } + }); +} +var import_events3, SdkObject; +var init_instrumentation = __esm({ + "packages/playwright-core/src/server/instrumentation.ts"() { + "use strict"; + import_events3 = require("events"); + init_crypto(); + init_debugLogger(); + SdkObject = class extends import_events3.EventEmitter { + constructor(parent, guidPrefix, guid) { + super(); + this.guid = guid || `${guidPrefix || ""}@${createGuid()}`; + this.setMaxListeners(0); + this.attribution = { ...parent.attribution }; + this.instrumentation = parent.instrumentation; + } + apiLog(message) { + if (!this.attribution.playwright.options.isInternalPlaywright) + debugLogger.log("api", message); + } + closeReason() { + return this.attribution.worker?._closeReason || this.attribution.page?._closeReason || this.attribution.context?._closeReason || this.attribution.browser?._closeReason; + } + }; + } +}); + +// packages/playwright-core/src/server/debugger.ts +function matchesLocation(metadata, location2) { + return !!metadata.location?.file.includes(location2.file) && (location2.line === void 0 || metadata.location.line === location2.line) && (location2.column === void 0 || metadata.location.column === location2.column); +} +var symbol, kApiCallsFlushDelay, DebuggerEvent, Debugger; +var init_debugger = __esm({ + "packages/playwright-core/src/server/debugger.ts"() { + "use strict"; + init_protocolMetainfo(); + init_protocolFormatter(); + init_time(); + init_instrumentation(); + init_browserContext(); + symbol = /* @__PURE__ */ Symbol("Debugger"); + kApiCallsFlushDelay = 500; + DebuggerEvent = { + PausedStateChanged: "pausedstatechanged", + ApiCallsUpdated: "apicallsupdated" + }; + Debugger = class _Debugger extends SdkObject { + constructor(context) { + super(context, "debugger"); + this._pauseAt = {}; + this._enabled = false; + this._pauseBeforeWaitingActions = false; + this._apiCallsEnabled = false; + this._ongoingCalls = /* @__PURE__ */ new Map(); + this._apiCallsWithPendingUpdates = /* @__PURE__ */ new Set(); + this._muted = false; + this._context = context; + this._context[symbol] = this; + context.instrumentation.addListener(this, context, { order: "last" }); + this._context.once(BrowserContext.Events.Close, () => { + this._context.instrumentation.removeListener(this); + if (this._apiCallsFlushTimer) + clearTimeout(this._apiCallsFlushTimer); + }); + } + static { + this.Events = DebuggerEvent; + } + requestPause(progress2) { + if (this.isPaused()) + throw new Error("Debugger is already paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ next: true }); + } + doResume(progress2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.resume(); + } + next(progress2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ next: true }); + this.resume(); + } + runTo(progress2, location2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ location: location2 }); + this.resume(); + } + async setMuted(muted) { + this._muted = muted; + } + async onBeforeCall(progress2, sdkObject) { + const { metadata } = progress2; + if (!metadata.internal && metadata.method) + this._ongoingCalls.set(metadata.id, { metadata, sentLogCount: 0, status: "running" }); + if (this._apiCallsEnabled) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._flushApiCalls(); + } + if (this._muted || metadata.internal) + return; + const metainfo = getMetainfo(metadata); + const pauseOnPauseCall = this._enabled && metadata.type === "BrowserContext" && metadata.method === "pause"; + const pauseBeforeAction = !!this._pauseAt.next && !!metainfo?.pause && (this._pauseBeforeWaitingActions || !metainfo?.isAutoWaiting); + const pauseOnLocation = !!this._pauseAt.location && matchesLocation(metadata, this._pauseAt.location); + if (pauseOnPauseCall || pauseBeforeAction || pauseOnLocation) + await this._pause(progress2, sdkObject); + } + async onBeforeInputAction(progress2, sdkObject, point) { + const { metadata } = progress2; + const call = this._ongoingCalls.get(metadata.id); + if (call) { + call.actionPoint = point; + if (this._apiCallsEnabled) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._flushApiCalls(); + } + } + if (this._muted || metadata.internal) + return; + const metainfo = getMetainfo(metadata); + const pauseBeforeInput = !!this._pauseAt.next && !!metainfo?.pause && !!metainfo?.isAutoWaiting && !this._pauseBeforeWaitingActions; + if (pauseBeforeInput) + await this._pause(progress2, sdkObject); + } + async onAfterCall(progress2, sdkObject) { + const { metadata } = progress2; + const call = this._ongoingCalls.get(metadata.id); + if (!call) + return; + call.status = metadata.error ? "error" : "success"; + if (this._apiCallsEnabled) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._flushApiCalls(); + } + this._ongoingCalls.delete(metadata.id); + } + onCallLog(sdkObject, metadata, logName, message) { + if (this._apiCallsEnabled && this._ongoingCalls.has(metadata.id)) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._scheduleApiCallsFlush(); + } + } + enableApiCalls() { + if (this._apiCallsEnabled) + return; + this._apiCallsEnabled = true; + this._pauseBeforeWaitingActions = false; + for (const id of this._ongoingCalls.keys()) + this._apiCallsWithPendingUpdates.add(id); + this._flushApiCalls(); + } + _scheduleApiCallsFlush() { + if (this._apiCallsFlushTimer || !this._apiCallsWithPendingUpdates.size) + return; + this._apiCallsFlushTimer = setTimeout(() => this._flushApiCalls(), kApiCallsFlushDelay); + } + _flushApiCalls() { + if (this._apiCallsFlushTimer) { + clearTimeout(this._apiCallsFlushTimer); + this._apiCallsFlushTimer = void 0; + } + const updates = []; + for (const id of this._apiCallsWithPendingUpdates) { + const call = this._ongoingCalls.get(id); + if (!call) + continue; + updates.push({ + id: call.metadata.id, + title: renderFullTitleForCall(call.metadata, this._context._browser.sdkLanguage()) ?? "", + location: call.metadata.location, + newLogEntries: call.metadata.log.slice(call.sentLogCount), + actionPoint: call.actionPoint, + status: call.metadata.error ? "error" : call.status, + error: call.metadata.error?.error?.message + }); + call.sentLogCount = call.metadata.log.length; + } + this._apiCallsWithPendingUpdates.clear(); + if (updates.length) + this.emit(_Debugger.Events.ApiCallsUpdated, updates); + } + async _pause(progress2, sdkObject) { + const { metadata } = progress2; + if (this._muted || metadata.internal) + return; + if (this._pausedCall) + return; + this._pauseAt = {}; + metadata.pauseStartTime = monotonicTime(); + const result2 = new Promise((resolve) => { + this._pausedCall = { metadata, sdkObject, resolve }; + }); + this.emit(_Debugger.Events.PausedStateChanged); + return result2; + } + resume() { + if (!this._pausedCall) + return; + this._pausedCall.metadata.pauseEndTime = monotonicTime(); + this._pausedCall.resolve(); + this._pausedCall = void 0; + this.emit(_Debugger.Events.PausedStateChanged); + } + setPauseBeforeWaitingActions() { + if (this._apiCallsEnabled) + return; + this._pauseBeforeWaitingActions = true; + } + setPauseAt(at = {}) { + this._enabled = true; + this._pauseAt = at; + } + isPaused(metadata) { + if (metadata) + return this._pausedCall?.metadata === metadata; + return !!this._pausedCall; + } + pausedDetails() { + return this._pausedCall; + } + }; + } +}); + +// packages/playwright-core/src/server/dialog.ts +var Dialog, DialogManager; +var init_dialog = __esm({ + "packages/playwright-core/src/server/dialog.ts"() { + "use strict"; + init_assert(); + init_errors(); + init_instrumentation(); + Dialog = class extends SdkObject { + constructor(page, type3, message, onHandle, defaultValue) { + super(page, "dialog"); + this._handled = false; + this._closed = false; + this._page = page; + this._type = type3; + this._message = message; + this._onHandle = onHandle; + this._defaultValue = defaultValue || ""; + } + async accept(progress2, promptText) { + await progress2.race(this._accept(promptText)); + } + async dismiss(progress2) { + await progress2.race(this._dismiss()); + } + page() { + return this._page; + } + type() { + return this._type; + } + message() { + return this._message; + } + defaultValue() { + return this._defaultValue; + } + async _accept(promptText) { + assert(!this._handled, "Cannot accept dialog which is already handled!"); + this._handled = true; + this._page.browserContext.dialogManager._dialogWillClose(this); + await this._onHandle(true, promptText); + this._didClose(); + } + async _dismiss() { + assert(!this._handled, "Cannot dismiss dialog which is already handled!"); + this._handled = true; + this._page.browserContext.dialogManager._dialogWillClose(this); + await this._onHandle(false); + this._didClose(); + } + _didClose() { + if (this._closed) + return; + this._closed = true; + this._page.browserContext.dialogManager._dialogDidClose(this); + } + async _close() { + if (this._type === "beforeunload") + await this._accept(); + else + await this._dismiss(); + } + }; + DialogManager = class { + constructor(instrumentation) { + this._dialogHandlers = /* @__PURE__ */ new Set(); + this._dialogClosedListeners = /* @__PURE__ */ new Set(); + this._openedDialogs = /* @__PURE__ */ new Set(); + this._instrumentation = instrumentation; + } + dialogDidOpen(dialog) { + for (const frame of dialog.page().frameManager.frames()) + frame.invalidateNonStallingEvaluations(new EvaluationStalledError("JavaScript dialog interrupted evaluation")); + this._openedDialogs.add(dialog); + this._instrumentation.onDialog(dialog); + let hasHandlers = false; + for (const handler of this._dialogHandlers) { + if (handler(dialog)) + hasHandlers = true; + } + if (!hasHandlers) + dialog._close().catch(() => { + }); + } + _dialogWillClose(dialog) { + this._openedDialogs.delete(dialog); + } + _dialogDidClose(dialog) { + this._openedDialogs.delete(dialog); + for (const listener of this._dialogClosedListeners) + listener(dialog); + } + dialogWasClosedInBrowser(page) { + for (const dialog of this._openedDialogs) { + if (dialog.page() === page) + dialog._didClose(); + } + } + addDialogClosedListener(listener) { + this._dialogClosedListeners.add(listener); + } + removeDialogClosedListener(listener) { + this._dialogClosedListeners.delete(listener); + } + addDialogHandler(handler) { + this._dialogHandlers.add(handler); + } + removeDialogHandler(handler) { + this._dialogHandlers.delete(handler); + if (!this._dialogHandlers.size) { + for (const dialog of this._openedDialogs) + dialog._close().catch(() => { + }); + } + } + hasOpenDialogsForPage(page) { + return [...this._openedDialogs].some((dialog) => dialog.page() === page); + } + async closeBeforeUnloadDialogs() { + await Promise.all([...this._openedDialogs].map(async (dialog) => { + if (dialog.type() === "beforeunload") + await dialog._dismiss(); + })); + } + }; + } +}); + +// packages/playwright-core/src/server/network.ts +function filterCookies(cookies, urls) { + const parsedURLs = urls.map((s) => new URL(s)); + return cookies.filter((c) => { + if (!parsedURLs.length) + return true; + for (const parsedURL of parsedURLs) { + let domain = c.domain; + if (!domain.startsWith(".")) + domain = "." + domain; + if (!("." + parsedURL.hostname).endsWith(domain)) + continue; + if (!parsedURL.pathname.startsWith(c.path)) + continue; + if (parsedURL.protocol !== "https:" && !isLocalHostname(parsedURL.hostname) && c.secure) + continue; + return true; + } + return false; + }); +} +function isLocalHostname(hostname) { + return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname); +} +function isForbiddenHeader(name, value2) { + const lowerName = name.toLowerCase(); + if (FORBIDDEN_HEADER_NAMES.has(lowerName)) + return true; + if (lowerName.startsWith("proxy-")) + return true; + if (lowerName.startsWith("sec-")) + return true; + if (lowerName === "x-http-method" || lowerName === "x-http-method-override" || lowerName === "x-method-override") { + if (value2 && FORBIDDEN_METHODS.has(value2.toUpperCase())) + return true; + } + return false; +} +function applyHeadersOverrides(original, overrides) { + const forbiddenHeaders = original.filter((header) => isForbiddenHeader(header.name, header.value)); + const allowedHeaders = overrides.filter((header) => !isForbiddenHeader(header.name, header.value)); + return mergeHeaders([allowedHeaders, forbiddenHeaders]); +} +function hasClearCookiesFilter(options) { + return options.name !== void 0 || options.domain !== void 0 || options.path !== void 0; +} +function cookieMatchesClearFilter(cookie, options) { + const matches = (prop, value2) => { + if (value2 === void 0) + return true; + if (value2 instanceof RegExp) { + value2.lastIndex = 0; + return value2.test(cookie[prop]); + } + return cookie[prop] === value2; + }; + return matches("name", options.name) && matches("domain", options.domain) && matches("path", options.path); +} +function rewriteCookies(cookies) { + return cookies.map((c) => { + assert(c.url || c.domain && c.path, "Cookie should have a url or a domain/path pair"); + assert(!(c.url && c.domain), "Cookie should have either url or domain"); + assert(!(c.url && c.path), "Cookie should have either url or path"); + assert(!(c.expires && c.expires < 0 && c.expires !== -1), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed"); + assert(!(c.expires && c.expires > 0 && c.expires > kMaxCookieExpiresDateInSeconds), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed"); + const copy = { ...c }; + if (copy.url) { + assert(copy.url !== "about:blank", `Blank page can not have cookie "${c.name}"`); + assert(!copy.url.startsWith("data:"), `Data URL page can not have cookie "${c.name}"`); + const url3 = new URL(copy.url); + copy.domain = url3.hostname; + copy.path = url3.pathname.substring(0, url3.pathname.lastIndexOf("/") + 1); + copy.secure = url3.protocol === "https:"; + } + return copy; + }); +} +function parseURL2(url3) { + try { + return new URL(url3); + } catch (e) { + return null; + } +} +function stripFragmentFromUrl(url3) { + if (!url3.includes("#")) + return url3; + return url3.substring(0, url3.indexOf("#")); +} +function statusText(status) { + return STATUS_TEXTS[String(status)] || "Unknown"; +} +function singleHeader(name, value2) { + return [{ name, value: value2 }]; +} +function mergeHeaders(headers) { + const lowerCaseToValue = /* @__PURE__ */ new Map(); + const lowerCaseToOriginalCase = /* @__PURE__ */ new Map(); + for (const h of headers) { + if (!h) + continue; + for (const { name, value: value2 } of h) { + const lower = name.toLowerCase(); + lowerCaseToOriginalCase.set(lower, name); + lowerCaseToValue.set(lower, value2); + } + } + const result2 = []; + for (const [lower, value2] of lowerCaseToValue) + result2.push({ name: lowerCaseToOriginalCase.get(lower), value: value2 }); + return result2; +} +function headersSize(headers) { + let result2 = 0; + for (const header of headers) + result2 += header.name.length + header.value.length + 4; + return result2; +} +function requestHeadersSize(headers, url3, method2) { + let result2 = 4; + result2 += method2.length; + result2 += new URL(url3).pathname.length; + result2 += 8; + result2 += headersSize(headers); + return result2; +} +function responseHeadersSize(headers, statusText2) { + let result2 = 4; + result2 += 8; + result2 += 3; + result2 += statusText2.length; + result2 += headersSize(headers); + result2 += 2; + return result2; +} +var FORBIDDEN_HEADER_NAMES, FORBIDDEN_METHODS, kMaxCookieExpiresDateInSeconds, Request, Route, Response2, WebSocket, STATUS_TEXTS; +var init_network2 = __esm({ + "packages/playwright-core/src/server/network.ts"() { + "use strict"; + init_manualPromise(); + init_assert(); + init_stackTrace(); + init_protocolError(); + init_browserContext(); + init_fetch(); + init_instrumentation(); + FORBIDDEN_HEADER_NAMES = /* @__PURE__ */ new Set([ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "date", + "dnt", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "set-cookie", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via" + ]); + FORBIDDEN_METHODS = /* @__PURE__ */ new Set(["CONNECT", "TRACE", "TRACK"]); + kMaxCookieExpiresDateInSeconds = 253402300799; + Request = class _Request extends SdkObject { + constructor(context, frame, serviceWorker, redirectedFrom, documentId, url3, resourceType, method2, postData, headers, wallTimeMs) { + super(frame || context, "request"); + this._response = null; + this._redirectedTo = null; + this._failureText = null; + this._frame = null; + this._serviceWorker = null; + this._rawRequestHeadersPromise = new ManualPromise(); + this._waitForResponsePromise = new ManualPromise(); + this._responseEndTiming = -1; + assert(!url3.startsWith("data:"), "Data urls should not fire requests"); + this._context = context; + this._frame = frame; + this._serviceWorker = serviceWorker; + this._redirectedFrom = redirectedFrom; + if (redirectedFrom) + redirectedFrom._redirectedTo = this; + this._documentId = documentId; + this._url = stripFragmentFromUrl(url3); + this._resourceType = resourceType; + this._method = method2; + this._postData = postData; + this._headers = headers; + this._wallTimeMs = wallTimeMs; + this._isFavicon = url3.endsWith("/favicon.ico") || !!redirectedFrom?._isFavicon; + } + static { + this.Events = { + Response: "response" + }; + } + wallTimeMs() { + return this._wallTimeMs; + } + async raceWithPageClosure(progress2, promise) { + const scope = this._serviceWorker?.openScope ?? this._frame?._page.openScope; + if (scope) + return await progress2.race(scope.race(promise)); + return await progress2.race(promise); + } + async rawRequestHeaders(progress2) { + return await this.raceWithPageClosure(progress2, this.internalRawRequestHeaders()); + } + async response(progress2) { + return await this.raceWithPageClosure(progress2, this._waitForResponse()); + } + _setFailureText(failureText) { + this._failureText = failureText; + this._waitForResponsePromise.resolve(null); + } + _applyOverrides(overrides) { + this._overrides = { ...this._overrides, ...overrides }; + return this._overrides; + } + overrides() { + return this._overrides; + } + url() { + return this._overrides?.url || this._url; + } + resourceType() { + return this._resourceType; + } + method() { + return this._overrides?.method || this._method; + } + postDataBuffer() { + return this._overrides?.postData || this._postData; + } + headers() { + return this._overrides?.headers || this._headers; + } + headerValue(name) { + const lowerCaseName = name.toLowerCase(); + return this.headers().find((h) => h.name.toLowerCase() === lowerCaseName)?.value; + } + // "null" means no raw headers available - we'll use provisional headers as raw headers. + setRawRequestHeaders(headers) { + if (!this._rawRequestHeadersPromise.isDone()) + this._rawRequestHeadersPromise.resolve(headers || this._headers); + } + async internalRawRequestHeaders() { + return this._overrides?.headers || this._rawRequestHeadersPromise; + } + _waitForResponse() { + return this._waitForResponsePromise; + } + _existingResponse() { + return this._response; + } + _setResponse(response2) { + this._response = response2; + this._waitForResponsePromise.resolve(response2); + this.emit(_Request.Events.Response, response2); + } + _finalRequest() { + return this._redirectedTo ? this._redirectedTo._finalRequest() : this; + } + frame() { + return this._frame; + } + serviceWorker() { + return this._serviceWorker; + } + isNavigationRequest() { + return !!this._documentId; + } + redirectedFrom() { + return this._redirectedFrom; + } + failure() { + if (this._failureText === null) + return null; + return { + errorText: this._failureText + }; + } + // TODO(bidi): remove once post body is available. + _setBodySize(size) { + this._bodySize = size; + } + bodySize() { + return this._bodySize || this.postDataBuffer()?.length || 0; + } + async _requestHeadersSize() { + return requestHeadersSize(await this.internalRawRequestHeaders(), this.url(), this.method()); + } + }; + Route = class extends SdkObject { + constructor(request2, delegate) { + super(request2._frame || request2._context, "route"); + this._handled = false; + this._futureHandlers = []; + this._request = request2; + this._delegate = delegate; + this._request._context.addRouteInFlight(this); + } + handle(handlers) { + this._futureHandlers = [...handlers]; + this.continue({ isFallback: true }).catch(() => { + }); + } + async removeHandler(handler) { + this._futureHandlers = this._futureHandlers.filter((h) => h !== handler); + if (handler === this._currentHandler) { + await this.continue({ isFallback: true }).catch(() => { + }); + return; + } + } + request() { + return this._request; + } + async abort(errorCode = "failed") { + this._startHandling(); + this._request._context.emit(BrowserContext.Events.RequestAborted, this._request); + await this._delegate.abort(errorCode); + this._endHandling(); + } + redirectNavigationRequest(url3) { + this._startHandling(); + assert(this._request.isNavigationRequest()); + this._request.frame().redirectNavigation(url3, this._request._documentId, this._request.headerValue("referer")); + this._endHandling(); + } + async fulfill(overrides) { + this._startHandling(); + let body = overrides.body; + let isBase64 = overrides.isBase64 || false; + if (body === void 0) { + if (overrides.fetchResponseUid) { + const buffer = this._request._context.fetchRequest.fetchResponses.get(overrides.fetchResponseUid) || APIRequestContext.findResponseBody(overrides.fetchResponseUid); + assert(buffer, "Fetch response has been disposed"); + body = buffer.toString("base64"); + isBase64 = true; + } else { + body = ""; + isBase64 = false; + } + } else if (!overrides.status || overrides.status < 200 || overrides.status >= 400) { + this._request._responseBodyOverride = { body, isBase64 }; + } + const headers = [...overrides.headers || []]; + this._maybeAddCorsHeaders(headers); + this._request._context.emit(BrowserContext.Events.RequestFulfilled, this._request); + await this._delegate.fulfill({ + status: overrides.status || 200, + headers, + body, + isBase64 + }); + this._endHandling(); + } + // See https://github.com/microsoft/playwright/issues/12929 + _maybeAddCorsHeaders(headers) { + const origin = this._request.headerValue("origin"); + if (!origin) + return; + const requestUrl = new URL(this._request.url()); + if (!requestUrl.protocol.startsWith("http")) + return; + if (requestUrl.origin === origin.trim()) + return; + const corsHeader = headers.find(({ name }) => name === "access-control-allow-origin"); + if (corsHeader) + return; + headers.push({ name: "access-control-allow-origin", value: origin }); + headers.push({ name: "access-control-allow-credentials", value: "true" }); + headers.push({ name: "vary", value: "Origin" }); + } + async continue(overrides) { + if (overrides.url) { + const newUrl = new URL(overrides.url); + const oldUrl = new URL(this._request.url()); + if (oldUrl.protocol !== newUrl.protocol) + throw new Error("New URL must have same protocol as overridden URL"); + } + if (overrides.headers) { + overrides.headers = applyHeadersOverrides(this._request._headers, overrides.headers); + } + overrides = this._request._applyOverrides(overrides); + const nextHandler = this._futureHandlers.shift(); + if (nextHandler) { + this._currentHandler = nextHandler; + nextHandler(this, this._request); + return; + } + if (!overrides.isFallback) + this._request._context.emit(BrowserContext.Events.RequestContinued, this._request); + this._startHandling(); + await this._delegate.continue(overrides); + this._endHandling(); + } + _startHandling() { + assert(!this._handled, "Route is already handled!"); + this._handled = true; + this._currentHandler = void 0; + } + _endHandling() { + this._futureHandlers = []; + this._currentHandler = void 0; + this._request._context.removeRouteInFlight(this); + } + }; + Response2 = class extends SdkObject { + constructor(request2, status, statusText2, headers, timing, getResponseBodyCallback, fromServiceWorker) { + super(request2.frame() || request2._context, "response"); + this._finishedPromise = new ManualPromise(); + this._headersMap = /* @__PURE__ */ new Map(); + this._serverAddrPromise = new ManualPromise(); + this._securityDetailsPromise = new ManualPromise(); + this._rawResponseHeadersPromise = new ManualPromise(); + this._httpVersionPromise = new ManualPromise(); + this._encodedBodySizePromise = new ManualPromise(); + this._transferSizePromise = new ManualPromise(); + this._responseHeadersSizePromise = new ManualPromise(); + this._request = request2; + this._timing = timing; + this._status = status; + this._statusText = statusText2; + this._url = request2.url(); + this._headers = headers; + for (const { name, value: value2 } of this._headers) + this._headersMap.set(name.toLowerCase(), value2); + this._getResponseBodyCallback = getResponseBodyCallback; + this._request._setResponse(this); + this._fromServiceWorker = fromServiceWorker; + } + async body(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalBody()); + } + async securityDetails(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalSecurityDetails()); + } + async serverAddr(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalServerAddr()); + } + async rawResponseHeaders(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalRawResponseHeaders()); + } + async httpVersion(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalHttpVersion()); + } + async sizes(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalSizes()); + } + _serverAddrFinished(addr) { + this._serverAddrPromise.resolve(addr); + } + _securityDetailsFinished(securityDetails) { + this._securityDetailsPromise.resolve(securityDetails); + } + _requestFinished(responseEndTiming) { + this._request._responseEndTiming = Math.max(responseEndTiming, this._timing.responseStart); + if (this._timing.requestStart === -1) + this._timing.requestStart = this._request._responseEndTiming; + this._finishedPromise.resolve(); + } + _setHttpVersion(httpVersion) { + this._httpVersionPromise.resolve(httpVersion); + } + url() { + return this._url; + } + status() { + return this._status; + } + statusText() { + return this._statusText; + } + headers() { + return this._headers; + } + headerValue(name) { + return this._headersMap.get(name); + } + // "null" means no raw headers available - we'll use provisional headers as raw headers. + setRawResponseHeaders(headers) { + if (!this._rawResponseHeadersPromise.isDone()) + this._rawResponseHeadersPromise.resolve(headers || this._headers); + } + setTransferSize(size) { + this._transferSizePromise.resolve(size); + } + setEncodedBodySize(size) { + this._encodedBodySizePromise.resolve(size); + } + setResponseHeadersSize(size) { + this._responseHeadersSizePromise.resolve(size); + } + timing() { + return this._timing; + } + async internalSecurityDetails() { + return await this._securityDetailsPromise || null; + } + async internalServerAddr() { + return await this._serverAddrPromise || null; + } + async internalRawResponseHeaders() { + return await this._rawResponseHeadersPromise; + } + async internalBody() { + await this._finishedPromise; + if (this._status >= 300 && this._status <= 399) + throw new Error("Response body is unavailable for redirect responses"); + if (this._request._responseBodyOverride) { + const { body, isBase64 } = this._request._responseBodyOverride; + return Buffer.from(body, isBase64 ? "base64" : "utf-8"); + } + try { + return await this._getResponseBodyCallback(); + } catch (e) { + if (isProtocolError(e) && e.type === "error") + rewriteErrorMessage(e, e.message + "\nResponse body is not available for a response that was navigated away from. Read response.body() before triggering any navigation."); + throw e; + } + } + request() { + return this._request; + } + finished() { + return this._finishedPromise; + } + frame() { + return this._request.frame(); + } + async internalHttpVersion() { + const httpVersion = await this._httpVersionPromise || null; + if (!httpVersion) + return "HTTP/1.1"; + if (httpVersion === "http/1.1") + return "HTTP/1.1"; + if (httpVersion === "h2") + return "HTTP/2.0"; + return httpVersion; + } + fromServiceWorker() { + return this._fromServiceWorker; + } + async responseHeadersSize() { + const availableSize = await this._responseHeadersSizePromise; + if (availableSize !== null) + return availableSize; + return responseHeadersSize(await this._rawResponseHeadersPromise, this.statusText()); + } + async internalSizes() { + const requestHeadersSize2 = await this._request._requestHeadersSize(); + const responseHeadersSize2 = await this.responseHeadersSize(); + let encodedBodySize = await this._encodedBodySizePromise; + if (encodedBodySize === null) { + const headers = await this._rawResponseHeadersPromise; + const contentLength = headers.find((h) => h.name.toLowerCase() === "content-length")?.value; + encodedBodySize = contentLength ? +contentLength : 0; + } + let transferSize = await this._transferSizePromise; + if (transferSize === null) { + transferSize = responseHeadersSize2 + encodedBodySize; + } + return { + requestBodySize: this._request.bodySize(), + requestHeadersSize: requestHeadersSize2, + responseBodySize: encodedBodySize, + responseHeadersSize: responseHeadersSize2, + transferSize + }; + } + }; + WebSocket = class _WebSocket extends SdkObject { + constructor(parent, url3) { + super(parent, "ws"); + this._notified = false; + this._url = stripFragmentFromUrl(url3); + } + static { + this.Events = { + Close: "close", + SocketError: "socketerror", + FrameReceived: "framereceived", + FrameSent: "framesent", + Request: "request", + Response: "response" + }; + } + markAsNotified() { + if (this._notified) + return false; + this._notified = true; + return true; + } + url() { + return this._url; + } + wallTimeMs() { + return this._wallTimeMs; + } + setWallTimeMs(wallTimeMs) { + this._wallTimeMs = wallTimeMs; + } + requestSent(headers) { + this.emit(_WebSocket.Events.Request, { headers }); + } + responseReceived(status, statusText2, headers) { + this.emit(_WebSocket.Events.Response, { status, statusText: statusText2, headers }); + } + frameSent(opcode, data, wallTimeMs) { + this.emit(_WebSocket.Events.FrameSent, { opcode, data, wallTimeMs }); + } + frameReceived(opcode, data, wallTimeMs) { + this.emit(_WebSocket.Events.FrameReceived, { opcode, data, wallTimeMs }); + } + error(errorMessage) { + this.emit(_WebSocket.Events.SocketError, errorMessage); + } + closed() { + this.emit(_WebSocket.Events.Close); + } + }; + STATUS_TEXTS = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "Switch Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "510": "Not Extended", + "511": "Network Authentication Required" + }; + } +}); + +// packages/playwright-core/src/server/cookieStore.ts +function parseRawCookie(header) { + const pairs = header.split(";").filter((s) => s.trim().length > 0).map((p) => { + let key = ""; + let value3 = ""; + const separatorPos = p.indexOf("="); + if (separatorPos === -1) { + key = p.trim(); + } else { + key = p.slice(0, separatorPos).trim(); + value3 = p.slice(separatorPos + 1).trim(); + } + return [key, value3]; + }); + if (!pairs.length) + return null; + const [name, value2] = pairs[0]; + const cookie = { + name, + value: value2 + }; + let maxAgeExpires; + for (let i = 1; i < pairs.length; i++) { + const [name2, value3] = pairs[i]; + switch (name2.toLowerCase()) { + case "expires": + const expiresMs = +new Date(value3); + if (isFinite(expiresMs)) { + if (expiresMs <= 0) + cookie.expires = 0; + else + cookie.expires = Math.min(expiresMs / 1e3, kMaxCookieExpiresDateInSeconds); + } + break; + case "max-age": + if (/^-?\d+$/.test(value3)) { + const maxAgeSec = parseInt(value3, 10); + if (maxAgeSec <= 0) + maxAgeExpires = 0; + else + maxAgeExpires = Math.min(Date.now() / 1e3 + maxAgeSec, kMaxCookieExpiresDateInSeconds); + } + break; + case "domain": + cookie.domain = value3.toLocaleLowerCase() || ""; + if (cookie.domain && !cookie.domain.startsWith(".") && cookie.domain.includes(".")) + cookie.domain = "." + cookie.domain; + break; + case "path": + cookie.path = value3 || ""; + break; + case "secure": + cookie.secure = true; + break; + case "httponly": + cookie.httpOnly = true; + break; + case "samesite": + switch (value3.toLowerCase()) { + case "none": + cookie.sameSite = "None"; + break; + case "lax": + cookie.sameSite = "Lax"; + break; + case "strict": + cookie.sameSite = "Strict"; + break; + } + break; + } + } + if (maxAgeExpires !== void 0) + cookie.expires = maxAgeExpires; + return cookie; +} +function domainMatches(value2, domain) { + if (value2 === domain) + return true; + if (!domain.startsWith(".")) + return false; + value2 = "." + value2; + return value2.endsWith(domain); +} +function pathMatches(value2, path66) { + if (value2 === path66) + return true; + if (!value2.endsWith("/")) + value2 = value2 + "/"; + if (!path66.endsWith("/")) + path66 = path66 + "/"; + return value2.startsWith(path66); +} +var Cookie, CookieStore; +var init_cookieStore = __esm({ + "packages/playwright-core/src/server/cookieStore.ts"() { + "use strict"; + init_network2(); + Cookie = class { + constructor(data) { + this._raw = data; + } + _name() { + return this._raw.name; + } + // https://datatracker.ietf.org/doc/html/rfc6265#section-5.4 + matches(url3) { + if (this._raw.secure && (url3.protocol !== "https:" && !isLocalHostname(url3.hostname))) + return false; + if (!domainMatches(url3.hostname, this._raw.domain)) + return false; + if (!pathMatches(url3.pathname, this._raw.path)) + return false; + return true; + } + _equals(other) { + return this._raw.name === other._raw.name && this._raw.domain === other._raw.domain && this._raw.path === other._raw.path; + } + _networkCookie() { + return this._raw; + } + _updateExpiresFrom(other) { + this._raw.expires = other._raw.expires; + } + _expired() { + if (this._raw.expires === -1) + return false; + return this._raw.expires * 1e3 < Date.now(); + } + }; + CookieStore = class _CookieStore { + constructor() { + this._nameToCookies = /* @__PURE__ */ new Map(); + } + addCookies(cookies) { + for (const cookie of cookies) + this._addCookie(new Cookie(cookie)); + } + allCookies() { + const result2 = []; + for (const cookie of this._cookiesIterator()) + result2.push(cookie._networkCookie()); + return result2; + } + removeCookies(predicate) { + for (const [name, cookies] of this._nameToCookies) { + for (const cookie of cookies) { + if (predicate(cookie._networkCookie())) + cookies.delete(cookie); + } + if (cookies.size === 0) + this._nameToCookies.delete(name); + } + } + _addCookie(cookie) { + let set = this._nameToCookies.get(cookie._name()); + if (!set) { + set = /* @__PURE__ */ new Set(); + this._nameToCookies.set(cookie._name(), set); + } + for (const other of set) { + if (other._equals(cookie)) + set.delete(other); + } + set.add(cookie); + _CookieStore.pruneExpired(set); + } + *_cookiesIterator() { + for (const [name, cookies] of this._nameToCookies) { + _CookieStore.pruneExpired(cookies); + for (const cookie of cookies) + yield cookie; + if (cookies.size === 0) + this._nameToCookies.delete(name); + } + } + static pruneExpired(cookies) { + for (const cookie of cookies) { + if (cookie._expired()) + cookies.delete(cookie); + } + } + }; + } +}); + +// packages/playwright-core/src/server/formData.ts +function generateUniqueBoundaryString() { + const charCodes = []; + for (let i = 0; i < 16; i++) + charCodes.push(alphaNumericEncodingMap[Math.floor(Math.random() * alphaNumericEncodingMap.length)]); + return "----WebKitFormBoundary" + String.fromCharCode(...charCodes); +} +var mime2, MultipartFormData, alphaNumericEncodingMap; +var init_formData = __esm({ + "packages/playwright-core/src/server/formData.ts"() { + "use strict"; + mime2 = require("./utilsBundle").mime; + MultipartFormData = class { + constructor() { + this._chunks = []; + this._boundary = generateUniqueBoundaryString(); + } + contentTypeHeader() { + return `multipart/form-data; boundary=${this._boundary}`; + } + addField(name, value2) { + this._beginMultiPartHeader(name); + this._finishMultiPartHeader(); + this._chunks.push(Buffer.from(value2)); + this._finishMultiPartField(); + } + addFileField(name, value2) { + this._beginMultiPartHeader(name); + this._chunks.push(Buffer.from(`; filename="${value2.name}"`)); + this._chunks.push(Buffer.from(`\r +content-type: ${value2.mimeType || mime2.getType(value2.name) || "application/octet-stream"}`)); + this._finishMultiPartHeader(); + this._chunks.push(value2.buffer); + this._finishMultiPartField(); + } + finish() { + this._addBoundary(true); + return Buffer.concat(this._chunks); + } + _beginMultiPartHeader(name) { + this._addBoundary(); + this._chunks.push(Buffer.from(`content-disposition: form-data; name="${name}"`)); + } + _finishMultiPartHeader() { + this._chunks.push(Buffer.from(`\r +\r +`)); + } + _finishMultiPartField() { + this._chunks.push(Buffer.from(`\r +`)); + } + _addBoundary(isLastBoundary) { + this._chunks.push(Buffer.from("--" + this._boundary)); + if (isLastBoundary) + this._chunks.push(Buffer.from("--")); + this._chunks.push(Buffer.from("\r\n")); + } + }; + alphaNumericEncodingMap = [ + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 65, + 66 + ]; + } +}); + +// packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts +function loadDummyServerCertsIfNeeded() { + if (dummyServerTlsOptions) + return; + const { cert, key } = generateSelfSignedCertificate(); + dummyServerTlsOptions = { key, cert }; +} +function normalizeOrigin(origin) { + try { + return new URL(origin).origin; + } catch (error) { + return origin; + } +} +function convertClientCertificatesToTLSOptions(clientCertificates) { + if (!clientCertificates || !clientCertificates.length) + return; + const tlsOptions = { + pfx: [], + key: [], + cert: [] + }; + for (const cert of clientCertificates) { + if (cert.cert) + tlsOptions.cert.push(cert.cert); + if (cert.key) + tlsOptions.key.push({ pem: cert.key, passphrase: cert.passphrase }); + if (cert.pfx) + tlsOptions.pfx.push({ buf: cert.pfx, passphrase: cert.passphrase }); + } + return tlsOptions; +} +function getMatchingTLSOptionsForOrigin(clientCertificates, origin) { + const matchingCerts = clientCertificates?.filter( + (c) => normalizeOrigin(c.origin) === origin + ); + return convertClientCertificatesToTLSOptions(matchingCerts); +} +function rewriteToLocalhostIfNeeded(host) { + return host === "local.playwright" ? "localhost" : host; +} +function rewriteOpenSSLErrorIfNeeded(error) { + if (error.message !== "unsupported" && error.code !== "ERR_CRYPTO_UNSUPPORTED_OPERATION") + return error; + return rewriteErrorMessage(error, [ + "Unsupported TLS certificate.", + "Most likely, the security algorithm of the given certificate was deprecated by OpenSSL.", + "For more details, see https://github.com/openssl/openssl/blob/master/README-PROVIDERS.md#the-legacy-provider", + "You could probably modernize the certificate by following the steps at https://github.com/nodejs/node/issues/40672#issuecomment-1243648223" + ].join("\n")); +} +function parseALPNFromClientHello(buffer) { + if (buffer.length < 6) + return null; + if (buffer[0] !== 22) + return null; + let offset = 5; + if (buffer[offset] !== 1) + return null; + offset += 4; + offset += 2; + offset += 32; + if (offset >= buffer.length) + return null; + const sessionIdLength = buffer[offset]; + offset += 1 + sessionIdLength; + if (offset + 2 > buffer.length) + return null; + const cipherSuitesLength = buffer.readUInt16BE(offset); + offset += 2 + cipherSuitesLength; + if (offset >= buffer.length) + return null; + const compressionMethodsLength = buffer[offset]; + offset += 1 + compressionMethodsLength; + if (offset + 2 > buffer.length) + return null; + const extensionsLength = buffer.readUInt16BE(offset); + offset += 2; + const extensionsEnd = offset + extensionsLength; + if (extensionsEnd > buffer.length) + return null; + while (offset + 4 <= extensionsEnd) { + const extensionType = buffer.readUInt16BE(offset); + offset += 2; + const extensionLength = buffer.readUInt16BE(offset); + offset += 2; + if (offset + extensionLength > extensionsEnd) + return null; + if (extensionType === 16) + return parseALPNExtension(buffer.subarray(offset, offset + extensionLength)); + offset += extensionLength; + } + return null; +} +function parseALPNExtension(buffer) { + if (buffer.length < 2) + return null; + const listLength = buffer.readUInt16BE(0); + if (listLength !== buffer.length - 2) + return null; + const protocols = []; + let offset = 2; + while (offset < buffer.length) { + const protocolLength = buffer[offset]; + offset += 1; + if (offset + protocolLength > buffer.length) + break; + const protocol = buffer.subarray(offset, offset + protocolLength).toString("utf8"); + protocols.push(protocol); + offset += protocolLength; + } + return protocols.length > 0 ? protocols : null; +} +var import_events4, import_http22, import_net3, import_stream2, import_tls, getProxyForUrl2, dummyServerTlsOptions, SocksProxyConnection, ClientCertificatesProxy; +var init_socksClientCertificatesInterceptor = __esm({ + "packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts"() { + "use strict"; + import_events4 = require("events"); + import_http22 = __toESM(require("http2")); + import_net3 = __toESM(require("net")); + import_stream2 = __toESM(require("stream")); + import_tls = __toESM(require("tls")); + init_socksProxy(); + init_debugLogger(); + init_stringUtils(); + init_crypto(); + init_stackTrace(); + init_network(); + init_browserContext(); + ({ getProxyForUrl: getProxyForUrl2 } = require("./utilsBundle")); + dummyServerTlsOptions = void 0; + SocksProxyConnection = class { + constructor(socksProxy, uid, host, port) { + this._firstPackageReceived = false; + this._closed = false; + this.socksProxy = socksProxy; + this.uid = uid; + this.host = host; + this.port = port; + this._serverCloseEventListener = async () => { + await this._brorwserDecrypted?.catch(() => { + }); + this._browserEncrypted.destroy(); + }; + this._browserEncrypted = new import_stream2.default.Duplex({ + read: () => { + }, + write: (data, encoding, callback) => { + this.socksProxy._socksProxy.sendSocketData({ uid: this.uid, data }); + callback(); + }, + destroy: (error, callback) => { + if (error) + socksProxy._socksProxy.sendSocketError({ uid: this.uid, error: error.message }); + else + socksProxy._socksProxy.sendSocketEnd({ uid: this.uid }); + callback(); + } + }); + } + async connect() { + const proxyAgent = this.socksProxy._getProxyAgent(this.host, this.port); + if (proxyAgent) + this._serverEncrypted = await proxyAgent.connect(new import_events4.EventEmitter(), { host: rewriteToLocalhostIfNeeded(this.host), port: this.port, secureEndpoint: false }); + else + this._serverEncrypted = await createSocket(rewriteToLocalhostIfNeeded(this.host), this.port); + this._serverEncrypted.once("close", this._serverCloseEventListener); + this._serverEncrypted.once("error", (error) => this._browserEncrypted.destroy(error)); + if (this._closed) { + this._serverEncrypted.destroy(); + return; + } + this.socksProxy._socksProxy.socketConnected({ + uid: this.uid, + host: this._serverEncrypted.localAddress, + port: this._serverEncrypted.localPort + }); + } + onClose() { + this._serverEncrypted.destroy(); + this._browserEncrypted.destroy(); + this._closed = true; + } + onData(data) { + if (!this._firstPackageReceived) { + this._firstPackageReceived = true; + const secureContext = data[0] === 22 ? this.socksProxy.secureContextMap.get(normalizeOrigin(`https://${this.host}:${this.port}`)) : void 0; + if (secureContext) + this._establishTlsTunnel(this._browserEncrypted, data, secureContext); + else + this._establishPlaintextTunnel(this._browserEncrypted); + } + this._browserEncrypted.push(data); + } + _establishPlaintextTunnel(browserEncrypted) { + browserEncrypted.pipe(this._serverEncrypted); + this._serverEncrypted.pipe(browserEncrypted); + } + _establishTlsTunnel(browserEncrypted, clientHello, secureContext) { + const browserALPNProtocols = parseALPNFromClientHello(clientHello) || ["http/1.1"]; + debugLogger.log("client-certificates", `Browser->Proxy ${this.host}:${this.port} offers ALPN ${browserALPNProtocols}`); + const rejectUnauthorized = !this.socksProxy.ignoreHTTPSErrors; + const serverDecrypted = import_tls.default.connect({ + socket: this._serverEncrypted, + host: this.host, + port: this.port, + rejectUnauthorized, + ALPNProtocols: browserALPNProtocols, + servername: !import_net3.default.isIP(this.host) ? this.host : void 0, + secureContext + }, async () => { + const browserDecrypted = await this._upgradeToTLSIfNeeded(browserEncrypted, serverDecrypted.alpnProtocol); + debugLogger.log("client-certificates", `Proxy->Server ${this.host}:${this.port} chooses ALPN ${browserDecrypted.alpnProtocol}`); + browserDecrypted.pipe(serverDecrypted); + serverDecrypted.pipe(browserDecrypted); + const cleanup = (error) => this._serverEncrypted.destroy(error); + browserDecrypted.once("error", cleanup); + serverDecrypted.once("error", cleanup); + browserDecrypted.once("close", cleanup); + serverDecrypted.once("close", cleanup); + if (this._closed) + serverDecrypted.destroy(); + }); + serverDecrypted.once("error", async (error) => { + debugLogger.log("client-certificates", `error when connecting to server: ${error.message.replaceAll("\n", " ")}`); + this._serverEncrypted.removeListener("close", this._serverCloseEventListener); + this._serverEncrypted.destroy(); + const browserDecrypted = await this._upgradeToTLSIfNeeded(this._browserEncrypted, serverDecrypted.alpnProtocol); + const responseBody = escapeHTML("Playwright client-certificate error: " + error.message).replaceAll("\n", "
"); + if (browserDecrypted.alpnProtocol === "h2") { + if ("performServerHandshake" in import_http22.default) { + const session = import_http22.default.performServerHandshake(browserDecrypted); + session.on("error", (error2) => { + this._browserEncrypted.destroy(error2); + }); + session.once("stream", (stream4) => { + const cleanup = (error2) => { + session.close(); + this._browserEncrypted.destroy(error2); + }; + stream4.once("end", cleanup); + stream4.once("error", cleanup); + stream4.respond({ + [import_http22.default.constants.HTTP2_HEADER_CONTENT_TYPE]: "text/html", + [import_http22.default.constants.HTTP2_HEADER_STATUS]: 503 + }); + stream4.end(responseBody); + }); + } else { + this._browserEncrypted.destroy(error); + } + } else { + browserDecrypted.end([ + "HTTP/1.1 503 Internal Server Error", + "Content-Type: text/html; charset=utf-8", + "Content-Length: " + Buffer.byteLength(responseBody), + "", + responseBody + ].join("\r\n")); + } + }); + } + async _upgradeToTLSIfNeeded(socket, alpnProtocol) { + this._brorwserDecrypted ??= new Promise((resolve, reject) => { + const dummyServer = import_tls.default.createServer({ + ...dummyServerTlsOptions, + ALPNProtocols: [alpnProtocol || "http/1.1"] + }); + dummyServer.emit("connection", socket); + dummyServer.once("secureConnection", (tlsSocket) => { + dummyServer.close(); + resolve(tlsSocket); + }); + dummyServer.once("error", (error) => { + dummyServer.close(); + reject(error); + }); + }); + return this._brorwserDecrypted; + } + }; + ClientCertificatesProxy = class _ClientCertificatesProxy { + constructor(contextOptions) { + this._connections = /* @__PURE__ */ new Map(); + this.secureContextMap = /* @__PURE__ */ new Map(); + verifyClientCertificates(contextOptions.clientCertificates); + this.ignoreHTTPSErrors = contextOptions.ignoreHTTPSErrors; + this._proxy = contextOptions.proxy; + this._initSecureContexts(contextOptions.clientCertificates); + this._socksProxy = new SocksProxy(); + this._socksProxy.setPattern("*"); + this._socksProxy.addListener(SocksProxy.Events.SocksRequested, async (payload) => { + try { + const connection = new SocksProxyConnection(this, payload.uid, payload.host, payload.port); + await connection.connect(); + this._connections.set(payload.uid, connection); + } catch (error) { + debugLogger.log("client-certificates", `Failed to connect to ${payload.host}:${payload.port}: ${error.message}`); + this._socksProxy.socketFailed({ uid: payload.uid, errorCode: error.code }); + } + }); + this._socksProxy.addListener(SocksProxy.Events.SocksData, (payload) => { + this._connections.get(payload.uid)?.onData(payload.data); + }); + this._socksProxy.addListener(SocksProxy.Events.SocksClosed, (payload) => { + this._connections.get(payload.uid)?.onClose(); + this._connections.delete(payload.uid); + }); + loadDummyServerCertsIfNeeded(); + } + _getProxyAgent(host, port) { + const url3 = new URL(`https://${import_net3.default.isIPv6(host) ? `[${host}]` : host}:${port}`); + if (this._proxy) + return createProxyAgent(this._proxy, url3); + const proxyFromEnv = getProxyForUrl2(url3.href); + if (proxyFromEnv) + return createProxyAgent({ server: proxyFromEnv }); + } + _initSecureContexts(clientCertificates) { + const origin2certs = /* @__PURE__ */ new Map(); + for (const cert of clientCertificates || []) { + const origin = normalizeOrigin(cert.origin); + const certs = origin2certs.get(origin) || []; + certs.push(cert); + origin2certs.set(origin, certs); + } + for (const [origin, certs] of origin2certs) { + try { + this.secureContextMap.set(origin, import_tls.default.createSecureContext(convertClientCertificatesToTLSOptions(certs))); + } catch (error) { + error = rewriteOpenSSLErrorIfNeeded(error); + throw rewriteErrorMessage(error, `Failed to load client certificate: ${error.message}`); + } + } + } + static async create(progress2, contextOptions) { + const proxy = new _ClientCertificatesProxy(contextOptions); + try { + await progress2.race(proxy._socksProxy.listen(0, "127.0.0.1")); + return proxy; + } catch (error) { + await progress2.race(proxy.close()); + throw error; + } + } + proxySettings() { + return { server: `socks5://127.0.0.1:${this._socksProxy.port()}` }; + } + async close() { + await this._socksProxy.close(); + } + }; + } +}); + +// packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts +function frameSnapshotStreamer(snapshotStreamer, removeNoScript) { + if (window[snapshotStreamer]) + return; + const kShadowAttribute = "__playwright_shadow_root_"; + const kValueAttribute = "__playwright_value_"; + const kCheckedAttribute = "__playwright_checked_"; + const kSelectedAttribute = "__playwright_selected_"; + const kScrollTopAttribute = "__playwright_scroll_top_"; + const kScrollLeftAttribute = "__playwright_scroll_left_"; + const kStyleSheetAttribute = "__playwright_style_sheet_"; + const kTargetAttribute = "__playwright_target__"; + const kCustomElementsAttribute = "__playwright_custom_elements__"; + const kCurrentSrcAttribute = "__playwright_current_src__"; + const kBoundingRectAttribute = "__playwright_bounding_rect__"; + const kPopoverOpenAttribute = "__playwright_popover_open_"; + const kDialogOpenAttribute = "__playwright_dialog_open_"; + const kSnapshotFrameId = /* @__PURE__ */ Symbol("__playwright_snapshot_frameid_"); + const kCachedData = /* @__PURE__ */ Symbol("__playwright_snapshot_cache_"); + const kEndOfList = /* @__PURE__ */ Symbol("__playwright_end_of_list_"); + function resetCachedData(obj) { + delete obj[kCachedData]; + } + function ensureCachedData(obj) { + if (!obj[kCachedData]) + obj[kCachedData] = {}; + return obj[kCachedData]; + } + const kObserverConfig = { attributes: true, subtree: true }; + function removeHash2(url3) { + try { + const u = new URL(url3); + u.hash = ""; + return u.toString(); + } catch (e) { + return url3; + } + } + class Streamer { + constructor() { + this._lastSnapshotNumber = 0; + this._staleStyleSheets = /* @__PURE__ */ new Set(); + this._modifiedStyleSheets = /* @__PURE__ */ new Set(); + this._readingStyleSheet = false; + this._targetGeneration = 0; + this._nativeShadowRoot = window.ShadowRoot; + this._nativeFirstChild = Object.getOwnPropertyDescriptor(window.Node.prototype, "firstChild").get; + this._nativeNextSibling = Object.getOwnPropertyDescriptor(window.Node.prototype, "nextSibling").get; + const invalidateCSSGroupingRule = (rule) => { + if (rule.parentStyleSheet) + this._invalidateStyleSheet(rule.parentStyleSheet); + }; + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "insertRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "deleteRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "addRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "removeRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeGetter(window.CSSStyleSheet.prototype, "rules", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeGetter(window.CSSStyleSheet.prototype, "cssRules", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "replaceSync", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSGroupingRule.prototype, "insertRule", invalidateCSSGroupingRule); + this._interceptNativeMethod(window.CSSGroupingRule.prototype, "deleteRule", invalidateCSSGroupingRule); + this._interceptNativeGetter(window.CSSGroupingRule.prototype, "cssRules", invalidateCSSGroupingRule); + this._interceptNativeSetter(window.StyleSheet.prototype, "disabled", (sheet) => { + if (sheet instanceof CSSStyleSheet) + this._invalidateStyleSheet(sheet); + }); + this._interceptNativeAsyncMethod(window.CSSStyleSheet.prototype, "replace", (sheet) => this._invalidateStyleSheet(sheet)); + this._fakeBase = document.createElement("base"); + this._observer = new MutationObserver((list) => this._handleMutations(list)); + this._ensureObservingCurrentDocument(); + } + _refreshListenersWhenNeeded() { + this._refreshListeners(); + const customEventName = "__playwright_snapshotter_global_listeners_check__"; + let seenEvent = false; + const handleCustomEvent = () => seenEvent = true; + window.addEventListener(customEventName, handleCustomEvent); + const observer = new MutationObserver((entries) => { + const newDocumentElement = entries.some((entry) => Array.from(entry.addedNodes).includes(document.documentElement)); + if (newDocumentElement) { + seenEvent = false; + window.dispatchEvent(new CustomEvent(customEventName)); + if (!seenEvent) { + window.addEventListener(customEventName, handleCustomEvent); + this._refreshListeners(); + } + } + }); + observer.observe(document, { childList: true }); + } + _refreshListeners() { + document.addEventListener("__playwright_mark_target__", (event) => { + const target = event.composedPath()[0]; + if (target?.nodeType !== Node.ELEMENT_NODE) + return; + target.__playwright_target__ = this._targetGeneration; + }); + document.addEventListener("__playwright_reset_targets__", () => { + ++this._targetGeneration; + }); + } + _shadowRoot(element3) { + const shadowRoot = element3.shadowRoot; + return shadowRoot instanceof this._nativeShadowRoot ? shadowRoot : null; + } + _interceptNativeMethod(obj, method2, cb) { + const native = obj[method2]; + if (!native) + return; + obj[method2] = function(...args) { + const result2 = native.call(this, ...args); + cb(this, result2); + return result2; + }; + } + _interceptNativeAsyncMethod(obj, method2, cb) { + const native = obj[method2]; + if (!native) + return; + obj[method2] = async function(...args) { + const result2 = await native.call(this, ...args); + cb(this, result2); + return result2; + }; + } + _interceptNativeGetter(obj, prop, cb) { + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); + Object.defineProperty(obj, prop, { + ...descriptor, + get: function() { + const result2 = descriptor.get.call(this); + cb(this, result2); + return result2; + } + }); + } + _interceptNativeSetter(obj, prop, cb) { + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); + Object.defineProperty(obj, prop, { + ...descriptor, + set: function(value2) { + const result2 = descriptor.set.call(this, value2); + cb(this, value2); + return result2; + } + }); + } + _handleMutations(list) { + for (const mutation of list) + ensureCachedData(mutation.target).attributesCached = void 0; + } + _ensureObservingCurrentDocument() { + if (this._observedDocument === document) + return; + this._observedDocument = document; + this._observer.disconnect(); + this._observer.observe(document, kObserverConfig); + this._refreshListenersWhenNeeded(); + } + _invalidateStyleSheet(sheet) { + if (this._readingStyleSheet) + return; + this._staleStyleSheets.add(sheet); + if (sheet.href !== null) + this._modifiedStyleSheets.add(sheet); + } + _updateStyleElementStyleSheetTextIfNeeded(sheet, forceText) { + const data = ensureCachedData(sheet); + if (this._staleStyleSheets.has(sheet) || forceText && data.cssText === void 0) { + this._staleStyleSheets.delete(sheet); + try { + data.cssText = this._getSheetText(sheet); + } catch (e) { + data.cssText = ""; + } + } + return data.cssText; + } + // Returns either content, ref, or no override. + _updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber) { + const data = ensureCachedData(sheet); + if (this._staleStyleSheets.has(sheet)) { + this._staleStyleSheets.delete(sheet); + try { + data.cssText = this._getSheetText(sheet); + data.cssRef = snapshotNumber; + return data.cssText; + } catch (e) { + } + } + return data.cssRef === void 0 ? void 0 : snapshotNumber - data.cssRef; + } + markIframe(iframeElement, frameId) { + iframeElement[kSnapshotFrameId] = frameId; + } + resetHistory() { + this._staleStyleSheets.clear(); + const visitNode = (node) => { + resetCachedData(node); + if (node.nodeType === Node.ELEMENT_NODE) { + const shadowRoot = this._shadowRoot(node); + if (shadowRoot) + visitNode(shadowRoot); + } + for (let child = this._nativeFirstChild.call(node); child; child = this._nativeNextSibling.call(child)) + visitNode(child); + }; + visitNode(document.documentElement); + visitNode(this._fakeBase); + } + __sanitizeMetaAttribute(name, value2, httpEquiv) { + if (name === "charset") + return "utf-8"; + if (httpEquiv.toLowerCase() !== "content-type" || name !== "content") + return value2; + const [type3, ...params2] = value2.split(";"); + if (type3 !== "text/html" || params2.length <= 0) + return value2; + const charsetParamIdx = params2.findIndex((param) => param.trim().startsWith("charset=")); + if (charsetParamIdx > -1) + params2[charsetParamIdx] = "charset=utf-8"; + return `${type3}; ${params2.join("; ")}`; + } + _sanitizeUrl(url3) { + if (url3.startsWith("javascript:") || url3.startsWith("vbscript:")) + return ""; + return url3; + } + _sanitizeSrcSet(srcset) { + return srcset.split(",").map((src) => { + src = src.trim(); + const spaceIndex = src.lastIndexOf(" "); + if (spaceIndex === -1) + return this._sanitizeUrl(src); + return this._sanitizeUrl(src.substring(0, spaceIndex).trim()) + src.substring(spaceIndex); + }).join(", "); + } + _resolveUrl(base, url3) { + if (url3 === "") + return ""; + try { + return new URL(url3, base).href; + } catch (e) { + return url3; + } + } + _getSheetBase(sheet) { + let rootSheet = sheet; + while (rootSheet.parentStyleSheet) + rootSheet = rootSheet.parentStyleSheet; + if (rootSheet.ownerNode) + return rootSheet.ownerNode.baseURI; + return document.baseURI; + } + _getSheetText(sheet) { + this._readingStyleSheet = true; + try { + if (sheet.disabled) + return ""; + const rules = []; + for (const rule of sheet.cssRules) + rules.push(rule.cssText); + return rules.join("\n"); + } finally { + this._readingStyleSheet = false; + } + } + captureSnapshot(reset) { + const timestamp = performance.now(); + const snapshotNumber = ++this._lastSnapshotNumber; + if (reset === "history") + this.resetHistory(); + if (reset) + ++this._targetGeneration; + let nodeCounter = 0; + let shadowDomNesting = 0; + let headNesting = 0; + this._ensureObservingCurrentDocument(); + this._handleMutations(this._observer.takeRecords()); + const definedCustomElements = /* @__PURE__ */ new Set(); + const visitNode = (node) => { + const nodeType = node.nodeType; + const nodeName = nodeType === Node.DOCUMENT_FRAGMENT_NODE ? "template" : node.nodeName; + if (nodeType !== Node.ELEMENT_NODE && nodeType !== Node.DOCUMENT_FRAGMENT_NODE && nodeType !== Node.TEXT_NODE) + return; + if (nodeName === "SCRIPT") + return; + if (nodeName === "LINK" && nodeType === Node.ELEMENT_NODE) { + const rel = node.getAttribute("rel")?.toLowerCase(); + if (rel === "preload" || rel === "prefetch") + return; + } + if (removeNoScript && nodeName === "NOSCRIPT") + return; + if (nodeName === "META") { + const httpEquiv = node.httpEquiv.toLowerCase(); + if (httpEquiv === "content-security-policy" || httpEquiv === "refresh" || httpEquiv === "set-cookie") + return; + } + if ((nodeName === "IFRAME" || nodeName === "FRAME") && headNesting) + return; + const data = ensureCachedData(node); + const values = []; + let equals = !!data.cached; + let extraNodes = 0; + const expectValue = (value2) => { + equals = equals && data.cached[values.length] === value2; + values.push(value2); + }; + const checkAndReturn = (n) => { + data.attributesCached = true; + if (equals) + return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] }; + nodeCounter += extraNodes; + data.ref = [snapshotNumber, nodeCounter++]; + data.cached = values; + return { equals: false, n }; + }; + if (nodeType === Node.TEXT_NODE) { + const value2 = node.nodeValue || ""; + expectValue(value2); + return checkAndReturn(value2); + } + if (nodeName === "STYLE") { + const sheet = node.sheet; + let cssText; + if (sheet) + cssText = this._updateStyleElementStyleSheetTextIfNeeded(sheet); + cssText = cssText || node.textContent || ""; + expectValue(cssText); + extraNodes++; + return checkAndReturn([nodeName, {}, cssText]); + } + const attrs = {}; + const result3 = [nodeName, attrs]; + const visitChild = (child) => { + const snapshot3 = visitNode(child); + if (snapshot3) { + result3.push(snapshot3.n); + expectValue(child); + equals = equals && snapshot3.equals; + } + }; + const visitChildStyleSheet = (child) => { + const snapshot3 = visitStyleSheet(child); + if (snapshot3) { + result3.push(snapshot3.n); + expectValue(child); + equals = equals && snapshot3.equals; + } + }; + if (nodeType === Node.DOCUMENT_FRAGMENT_NODE) + attrs[kShadowAttribute] = "open"; + if (nodeType === Node.ELEMENT_NODE) { + const element3 = node; + if (element3.localName.includes("-") && window.customElements?.get(element3.localName)) + definedCustomElements.add(element3.localName); + if (nodeName === "INPUT" || nodeName === "TEXTAREA") { + const value2 = element3.value; + expectValue(kValueAttribute); + expectValue(value2); + attrs[kValueAttribute] = value2; + } + if (nodeName === "INPUT" && ["checkbox", "radio"].includes(element3.type)) { + const value2 = element3.checked ? "true" : "false"; + expectValue(kCheckedAttribute); + expectValue(value2); + attrs[kCheckedAttribute] = value2; + } + if (nodeName === "OPTION") { + const value2 = element3.selected ? "true" : "false"; + expectValue(kSelectedAttribute); + expectValue(value2); + attrs[kSelectedAttribute] = value2; + } + if (nodeName === "CANVAS" || nodeName === "IFRAME" || nodeName === "FRAME") { + const boundingRect = element3.getBoundingClientRect(); + const value2 = JSON.stringify({ + left: boundingRect.left, + top: boundingRect.top, + right: boundingRect.right, + bottom: boundingRect.bottom + }); + expectValue(kBoundingRectAttribute); + expectValue(value2); + attrs[kBoundingRectAttribute] = value2; + } + if (element3.popover && element3.matches && element3.matches(":popover-open")) { + const value2 = "true"; + expectValue(kPopoverOpenAttribute); + expectValue(value2); + attrs[kPopoverOpenAttribute] = value2; + } + if (nodeName === "DIALOG" && element3.open) { + const value2 = element3.matches(":modal") ? "modal" : "true"; + expectValue(kDialogOpenAttribute); + expectValue(value2); + attrs[kDialogOpenAttribute] = value2; + } + if (element3.scrollTop) { + expectValue(kScrollTopAttribute); + expectValue(element3.scrollTop); + attrs[kScrollTopAttribute] = "" + element3.scrollTop; + } + if (element3.scrollLeft) { + expectValue(kScrollLeftAttribute); + expectValue(element3.scrollLeft); + attrs[kScrollLeftAttribute] = "" + element3.scrollLeft; + } + const shadowRoot = this._shadowRoot(element3); + if (shadowRoot) { + ++shadowDomNesting; + visitChild(shadowRoot); + --shadowDomNesting; + } + if (element3.__playwright_target__ === this._targetGeneration) { + expectValue(kTargetAttribute); + attrs[kTargetAttribute] = ""; + } + } + if (nodeName === "HEAD") { + ++headNesting; + this._fakeBase.setAttribute("href", document.baseURI); + visitChild(this._fakeBase); + } + for (let child = this._nativeFirstChild.call(node); child; child = this._nativeNextSibling.call(child)) + visitChild(child); + if (nodeName === "HEAD") + --headNesting; + expectValue(kEndOfList); + let documentOrShadowRoot = null; + if (node.ownerDocument.documentElement === node) + documentOrShadowRoot = node.ownerDocument; + else if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) + documentOrShadowRoot = node; + if (documentOrShadowRoot) { + for (const sheet of documentOrShadowRoot.adoptedStyleSheets || []) + visitChildStyleSheet(sheet); + expectValue(kEndOfList); + } + if (nodeName === "IFRAME" || nodeName === "FRAME") { + const element3 = node; + const frameId = element3[kSnapshotFrameId]; + const name = "src"; + const value2 = frameId ? `/snapshot/${frameId}` : ""; + expectValue(name); + expectValue(value2); + attrs[name] = value2; + } + if (nodeName === "BODY" && definedCustomElements.size) { + const value2 = [...definedCustomElements].join(","); + expectValue(kCustomElementsAttribute); + expectValue(value2); + attrs[kCustomElementsAttribute] = value2; + } + if (nodeName === "IMG" || nodeName === "PICTURE") { + const value2 = nodeName === "PICTURE" ? "" : this._sanitizeUrl(node.currentSrc); + expectValue(kCurrentSrcAttribute); + expectValue(value2); + attrs[kCurrentSrcAttribute] = value2; + } + if (equals && data.attributesCached && !shadowDomNesting) + return checkAndReturn(result3); + if (nodeType === Node.ELEMENT_NODE) { + const element3 = node; + for (let i = 0; i < element3.attributes.length; i++) { + const name = element3.attributes[i].name; + if (nodeName === "LINK" && name === "integrity") + continue; + if (nodeName === "IFRAME" && (name === "src" || name === "srcdoc" || name === "sandbox")) + continue; + if (nodeName === "FRAME" && name === "src") + continue; + if (nodeName === "DIALOG" && name === "open") + continue; + let value2 = element3.attributes[i].value; + if (nodeName === "META") + value2 = this.__sanitizeMetaAttribute(name, value2, node.httpEquiv); + else if (name === "src" && nodeName === "IMG") + value2 = this._sanitizeUrl(value2); + else if (name === "srcset" && nodeName === "IMG") + value2 = this._sanitizeSrcSet(value2); + else if (name === "srcset" && nodeName === "SOURCE") + value2 = this._sanitizeSrcSet(value2); + else if (name === "href" && nodeName === "LINK") + value2 = this._sanitizeUrl(value2); + else if (name.startsWith("on")) + value2 = ""; + expectValue(name); + expectValue(value2); + attrs[name] = value2; + } + expectValue(kEndOfList); + } + if (result3.length === 2 && !Object.keys(attrs).length) + result3.pop(); + return checkAndReturn(result3); + }; + const visitStyleSheet = (sheet) => { + const data = ensureCachedData(sheet); + const oldCSSText = data.cssText; + const cssText = this._updateStyleElementStyleSheetTextIfNeeded( + sheet, + true + /* forceText */ + ); + if (cssText === oldCSSText) + return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] }; + data.ref = [snapshotNumber, nodeCounter++]; + return { + equals: false, + n: ["template", { + [kStyleSheetAttribute]: cssText + }] + }; + }; + let html; + if (document.documentElement) { + const { n } = visitNode(document.documentElement); + html = n; + } else { + html = ["html"]; + } + const result2 = { + html, + doctype: document.doctype ? document.doctype.name : void 0, + resourceOverrides: [], + viewport: { + width: window.innerWidth, + height: window.innerHeight + }, + url: location.href, + wallTime: Date.now(), + collectionTime: 0 + }; + for (const sheet of this._modifiedStyleSheets) { + if (sheet.href === null) + continue; + const content = this._updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber); + if (content === void 0) { + continue; + } + const base = this._getSheetBase(sheet); + const url3 = removeHash2(this._resolveUrl(base, sheet.href)); + result2.resourceOverrides.push({ url: url3, content, contentType: "text/css" }); + } + result2.collectionTime = performance.now() - timestamp; + return result2; + } + } + window[snapshotStreamer] = new Streamer(); +} +var init_snapshotterInjected = __esm({ + "packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/server/trace/recorder/snapshotter.ts +var mime3, Snapshotter, kNeedsResetSymbol; +var init_snapshotter = __esm({ + "packages/playwright-core/src/server/trace/recorder/snapshotter.ts"() { + "use strict"; + init_time(); + init_crypto(); + init_debugLogger(); + init_eventsHelper(); + init_snapshotterInjected(); + init_browserContext(); + init_progress(); + mime3 = require("./utilsBundle").mime; + Snapshotter = class { + constructor(context, delegate) { + this._eventListeners = []; + this._started = false; + this._context = context; + this._delegate = delegate; + const guid = createGuid(); + this._snapshotStreamer = "__playwright_snapshot_streamer_" + guid; + } + started() { + return this._started; + } + async start(progress2) { + this._started = true; + if (!this._initScript) + await this._initialize(progress2); + await progress2.race(this.reset()); + } + async reset() { + if (this._started) + await this._context.safeNonStallingEvaluateInAllFrames(`window["${this._snapshotStreamer}"].resetHistory()`, "main"); + } + stop() { + this._started = false; + } + async resetForReuse() { + if (this._initScript) { + eventsHelper.removeEventListeners(this._eventListeners); + await this._initScript.dispose(); + this._initScript = void 0; + } + } + async _initialize(progress2) { + for (const page of this._context.pages()) + this._onPage(page); + this._eventListeners = [ + eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, this._onPage.bind(this)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.FrameAttached, (frame) => this._annotateFrameHierarchy(frame)) + ]; + const { javaScriptEnabled } = this._context._options; + const initScriptSource = `(${frameSnapshotStreamer})("${this._snapshotStreamer}", ${javaScriptEnabled || javaScriptEnabled === void 0})`; + this._initScript = await this._context.addInitScript(progress2, initScriptSource); + await progress2.race(this._context.safeNonStallingEvaluateInAllFrames(initScriptSource, "main")); + } + dispose() { + eventsHelper.removeEventListeners(this._eventListeners); + } + async _captureFrameSnapshot(frame, resetTargets) { + const needsHistoryReset = !!frame[kNeedsResetSymbol]; + frame[kNeedsResetSymbol] = false; + const reset = needsHistoryReset ? "history" : resetTargets ? "targets" : void 0; + const expression2 = `window["${this._snapshotStreamer}"].captureSnapshot(${JSON.stringify(reset)})`; + try { + return await frame.nonStallingRawEvaluateInExistingMainContext(expression2); + } catch (e) { + frame[kNeedsResetSymbol] = true; + debugLogger.log("error", e); + } + } + async captureSnapshot(page, callId, phase, resetTargets) { + const snapshots = page.frames().map(async (frame) => { + const data = await this._captureFrameSnapshot(frame, resetTargets); + if (!data || !this._started) + return; + const snapshot3 = { + callId, + phase, + pageId: page.guid, + frameId: frame.guid, + frameUrl: data.url, + doctype: data.doctype, + html: data.html, + viewport: data.viewport, + timestamp: monotonicTime(), + wallTime: data.wallTime, + collectionTime: data.collectionTime, + resourceOverrides: [], + isMainFrame: page.mainFrame() === frame + }; + for (const { url: url3, content, contentType } of data.resourceOverrides) { + if (typeof content === "string") { + const buffer = Buffer.from(content); + const sha1 = calculateSha1(buffer) + "." + (mime3.getExtension(contentType) || "dat"); + const file = this._delegate.onSnapshotterBlob({ sha1, buffer }); + snapshot3.resourceOverrides.push({ url: url3, file }); + } else { + snapshot3.resourceOverrides.push({ url: url3, ref: content }); + } + } + this._delegate.onFrameSnapshot(snapshot3); + }); + await Promise.all(snapshots); + } + _onPage(page) { + for (const frame of page.frames()) + this._annotateFrameHierarchy(frame); + } + _annotateFrameHierarchy(frame) { + (async () => { + const frameElement = await frame.frameElement(nullProgress); + const parent = frame.parentFrame(); + if (!parent) + return; + const context = await parent.mainContext(); + await context?.evaluate(({ snapshotStreamer, frameElement: frameElement2, frameId }) => { + window[snapshotStreamer].markIframe(frameElement2, frameId); + }, { snapshotStreamer: this._snapshotStreamer, frameElement, frameId: frame.guid }); + frameElement.dispose(); + })().catch(() => { + }); + } + }; + kNeedsResetSymbol = /* @__PURE__ */ Symbol("kNeedsReset"); + } +}); + +// packages/playwright-core/src/server/artifact.ts +var import_fs11, Artifact; +var init_artifact = __esm({ + "packages/playwright-core/src/server/artifact.ts"() { + "use strict"; + import_fs11 = __toESM(require("fs")); + init_manualPromise(); + init_assert(); + init_errors(); + init_instrumentation(); + Artifact = class extends SdkObject { + constructor(parent, localPath, unaccessibleErrorMessage, cancelCallback) { + super(parent, "artifact"); + this._finishedPromise = new ManualPromise(); + this._saveCallbacks = []; + this._finished = false; + this._deleted = false; + this._localPath = localPath; + this._unaccessibleErrorMessage = unaccessibleErrorMessage; + this._cancelCallback = cancelCallback; + } + async localPathAfterFinished(progress2) { + return await progress2.race(this._localPathAfterFinished()); + } + async failureError(progress2) { + return await progress2.race(this._failureError()); + } + async cancel(progress2) { + return await progress2.race(this._cancel()); + } + async delete(progress2) { + return await progress2.race(this._delete()); + } + localPath() { + return this._localPath; + } + async _localPathAfterFinished() { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + await this._finishedPromise; + if (this._failureErrorValue) + throw this._failureErrorValue; + return this._localPath; + } + saveAs(progress2, saveCallback) { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + if (this._deleted) + throw new Error(`File already deleted. Save before deleting.`); + if (this._failureErrorValue) + throw this._failureErrorValue; + if (this._finished) { + saveCallback(this._localPath).catch(() => { + }); + return; + } + this._saveCallbacks.push(saveCallback); + } + async _failureError() { + if (this._unaccessibleErrorMessage) + return this._unaccessibleErrorMessage; + await this._finishedPromise; + return this._failureErrorValue?.message || null; + } + async _cancel() { + assert(this._cancelCallback !== void 0); + return this._cancelCallback(); + } + async _delete() { + if (this._unaccessibleErrorMessage) + return; + const fileName = await this._localPathAfterFinished(); + if (this._deleted) + return; + this._deleted = true; + if (fileName) + await import_fs11.default.promises.unlink(fileName).catch((e) => { + }); + } + async deleteOnContextClose() { + if (this._deleted) + return; + this._deleted = true; + if (!this._unaccessibleErrorMessage) + await import_fs11.default.promises.unlink(this._localPath).catch((e) => { + }); + await this.reportFinished(new TargetClosedError(this.closeReason())); + } + async reportFinished(error) { + if (this._finished) + return; + this._finished = true; + this._failureErrorValue = error; + if (error) { + for (const callback of this._saveCallbacks) + await callback("", error); + } else { + for (const callback of this._saveCallbacks) + await callback(this._localPath); + } + this._saveCallbacks = []; + this._finishedPromise.resolve(); + } + }; + } +}); + +// packages/playwright-core/src/generated/coverageScriptSource.ts +var source3; +var init_coverageScriptSource = __esm({ + "packages/playwright-core/src/generated/coverageScriptSource.ts"() { + "use strict"; + source3 = ` +var __commonJS = obj => { + let required = false; + let result; + return function __require() { + if (!required) { + required = true; + let fn; + for (const name in obj) { fn = obj[name]; break; } + const module = { exports: {} }; + fn(module.exports, module); + result = module.exports; + } + return result; + } +}; +var __export = (target, all) => {for (var name in all) target[name] = all[name];}; +var __toESM = mod => ({ ...mod, 'default': mod }); +var __toCommonJS = mod => ({ ...mod, __esModule: true }); + + +// packages/injected/src/coverageScript.ts +var coverageScript_exports = {}; +__export(coverageScript_exports, { + CoverageScript: () => CoverageScript, + takeCoverageStashes: () => takeCoverageStashes +}); +module.exports = __toCommonJS(coverageScript_exports); + +// packages/isomorphic/istanbulCoverage.ts +var kCoverageStashPrefix = "__pwCoverage."; +var kCoverageStashError = "Failed to stash the coverage"; +function takeCounters(counters) { + let result; + for (const key of Object.keys(counters)) { + const count = counters[key]; + if (!count) + continue; + if (!result) + result = {}; + result[key] = count; + counters[key] = 0; + } + return result; +} +function takeBranchCounters(counters) { + let result; + for (const key of Object.keys(counters)) { + const counts = counters[key]; + if (!counts.some(Boolean)) + continue; + if (!result) + result = {}; + result[key] = counts.slice(); + counts.fill(0); + } + return result; +} + +// packages/injected/src/coverageScript.ts +var CoverageScript = class { + constructor(global, takeName, sessionId) { + this._reportedFiles = /* @__PURE__ */ new Set(); + this._onPageHide = () => this._stashCurrent(); + this._global = global; + this._takeName = takeName; + this._sessionId = sessionId; + global[takeName] = Object.assign(() => this.take(), { dispose: () => this.dispose() }); + this._resetCounters(); + global.addEventListener("pagehide", this._onPageHide); + } + _resetCounters() { + const coverage = this._global.__coverage__; + for (const fileCoverage of Object.values(coverage || {})) { + takeCounters(fileCoverage.s); + takeCounters(fileCoverage.f); + takeBranchCounters(fileCoverage.b); + } + } + dispose() { + this._global.removeEventListener("pagehide", this._onPageHide); + delete this._global[this._takeName]; + } + take() { + const chunks = takeCoverageStashes(this._global, this._sessionId); + const delta = this._takeCurrent(); + if (delta) + chunks.push(JSON.stringify({ data: delta })); + return chunks; + } + _takeCurrent() { + const coverage = this._global.__coverage__; + if (!coverage) + return void 0; + const delta = {}; + for (const [file, fileCoverage] of Object.entries(coverage)) { + const s = takeCounters(fileCoverage.s); + const f = takeCounters(fileCoverage.f); + const b = takeBranchCounters(fileCoverage.b); + const isFirstReport = !this._reportedFiles.has(file); + if (!isFirstReport && !s && !f && !b) + continue; + const entry = { path: fileCoverage.path, s: s || {}, f: f || {}, b: b || {} }; + if (isFirstReport) { + entry.statementMap = fileCoverage.statementMap; + entry.fnMap = fileCoverage.fnMap; + entry.branchMap = fileCoverage.branchMap; + this._reportedFiles.add(file); + } + delta[file] = entry; + } + return Object.keys(delta).length ? delta : void 0; + } + _stashCurrent() { + const delta = this._takeCurrent(); + if (!delta) + return; + const id = Math.random().toString(36).slice(2); + try { + this._global.localStorage.setItem(kCoverageStashPrefix + this._sessionId + "." + id, JSON.stringify({ id, data: delta })); + } catch (error) { + try { + this._global.localStorage.setItem(stashErrorKey(this._sessionId), String(error)); + } catch { + } + } + } +}; +function stashErrorKey(sessionId) { + return kCoverageStashPrefix + "error." + sessionId; +} +function takeCoverageStashes(global, sessionId) { + const result = []; + let storage; + try { + storage = global.localStorage; + } catch { + return result; + } + const error = storage.getItem(stashErrorKey(sessionId)); + if (error) { + storage.removeItem(stashErrorKey(sessionId)); + throw new Error(kCoverageStashError + ": " + error); + } + const sessionPrefix = kCoverageStashPrefix + sessionId + "."; + const keys = []; + for (let i = 0; i < storage.length; i++) { + const key = storage.key(i); + if (key && key.startsWith(kCoverageStashPrefix)) + keys.push(key); + } + for (const key of keys) { + const json = key.startsWith(sessionPrefix) ? storage.getItem(key) : void 0; + storage.removeItem(key); + if (json) + result.push(json); + } + return result; +} +`; + } +}); + +// packages/playwright-core/src/server/coverageRecorder.ts +var kCoverageTakeName, coverageTakeExpression, coverageDisposeExpression, CoverageRecorder; +var init_coverageRecorder = __esm({ + "packages/playwright-core/src/server/coverageRecorder.ts"() { + "use strict"; + init_istanbulCoverage(); + init_coverageScriptSource(); + kCoverageTakeName = "__pwCoverageTake"; + coverageTakeExpression = `window[${JSON.stringify(kCoverageTakeName)}] ? window[${JSON.stringify(kCoverageTakeName)}]() : []`; + coverageDisposeExpression = `window[${JSON.stringify(kCoverageTakeName)}]?.dispose()`; + CoverageRecorder = class { + constructor(context) { + this._coverage = /* @__PURE__ */ new Map(); + this._stashedChunkIds = /* @__PURE__ */ new Set(); + this._context = context; + } + _moduleExpression(call) { + return `(() => { + const module = {}; + ${source3} + ${call} + })()`; + } + _sessionId() { + return JSON.stringify(this._context.guid); + } + async install(progress2) { + if (this._initScript) + return; + const source14 = this._moduleExpression(`new (module.exports.CoverageScript())(window, ${JSON.stringify(kCoverageTakeName)}, ${this._sessionId()});`); + this._initScript = await this._context.addInitScript(progress2, source14); + await progress2.race(this._context.safeNonStallingEvaluateInAllFrames(source14, "main")); + } + async uninstall() { + await Promise.all([ + this._initScript?.dispose(), + this._context.safeNonStallingEvaluateInAllFrames(coverageDisposeExpression, "main") + ]).catch(() => { + }); + } + async flush(progress2) { + await progress2.race(Promise.all(this._context.pages().map((page) => this.collectFromPage(page)))); + await this._harvestOriginsWithoutPage(progress2); + } + async take(progress2, mode) { + if (mode === "discard") { + this._coverage.clear(); + return; + } + await this.flush(progress2); + if (this._stashError) + throw this._stashError; + this._stashedChunkIds.clear(); + if (!this._coverage.size) + return; + const sorted = sortedIstanbulCoverage(this._coverage); + this._coverage.clear(); + return JSON.stringify(sorted); + } + async collectFromPage(page) { + if (page.isStorageStatePage) + return; + await Promise.race([page.closedPromise, this._collectFromPage(page)]); + } + async _collectFromPage(page) { + await Promise.all(page.frames().map(async (frame) => { + const chunks = await frame.nonStallingRawEvaluateInExistingMainContext(coverageTakeExpression).catch((error) => this._takeFailed(error)); + for (const json of chunks) + this._append(json); + })); + } + async _harvestOriginsWithoutPage(progress2) { + if (this._context.isClosingOrClosed()) + return; + const liveOrigins = /* @__PURE__ */ new Set(); + for (const page of this._context.pages()) { + for (const frame of page.frames()) { + const origin = frame.origin(); + if (origin) + liveOrigins.add(origin); + } + } + const origins = new Set([...this._context.visitedOrigins()].filter((origin) => !liveOrigins.has(origin))); + if (!origins.size) + return; + const source14 = this._moduleExpression(`return (module.exports.takeCoverageStashes())(window, ${this._sessionId()});`); + await this._context.visitOrigins(progress2, origins, async (frame) => { + const chunks = await frame.evaluateExpression(progress2, source14, { world: "main" }).catch((error) => this._takeFailed(error)); + for (const json of chunks) + this._append(json); + }); + } + // Evaluation fails for pages on their way out, only the stash error matters. + _takeFailed(error) { + const message = error.message?.split("\n")[0].replace(/^Error: /, ""); + if (message?.includes(kCoverageStashError)) + this._stashError ??= new Error(message); + return []; + } + _append(json) { + try { + const chunk = JSON.parse(json); + if (chunk.id) { + if (this._stashedChunkIds.has(chunk.id)) + return; + this._stashedChunkIds.add(chunk.id); + } + mergeIstanbulCoverage(this._coverage, chunk.data); + } catch { + } + } + }; + } +}); + +// packages/protocol/src/validatorPrimitives.ts +function findValidator(type3, method2, kind) { + const validator = maybeFindValidator(type3, method2, kind); + if (!validator) + throw new ValidationError(`Unknown scheme for ${kind}: ${type3}.${method2}`); + return validator; +} +function maybeFindValidator(type3, method2, kind) { + const schemeName = type3 + (kind === "Initializer" ? "" : method2[0].toUpperCase() + method2.substring(1)) + kind; + return scheme[schemeName]; +} +function createMetadataValidator() { + return tOptional(scheme["Metadata"]); +} +function createWaitInfoValidator() { + return scheme["WaitInfo"]; +} +var ValidationError, scheme, tFloat, tInt, tBoolean, tString, tBinary, tAny, tOptional, tArray, tObject, tEnum, tChannel, tType; +var init_validatorPrimitives = __esm({ + "packages/protocol/src/validatorPrimitives.ts"() { + "use strict"; + ValidationError = class extends Error { + }; + scheme = {}; + tFloat = (arg2, path66, context) => { + if (arg2 instanceof Number) + return arg2.valueOf(); + if (typeof arg2 === "number") + return arg2; + throw new ValidationError(`${path66}: expected float, got ${typeof arg2}`); + }; + tInt = (arg2, path66, context) => { + let value2; + if (arg2 instanceof Number) + value2 = arg2.valueOf(); + else if (typeof arg2 === "number") + value2 = arg2; + else + throw new ValidationError(`${path66}: expected integer, got ${typeof arg2}`); + if (!Number.isInteger(value2)) + throw new ValidationError(`${path66}: expected integer, got float ${value2}`); + return value2; + }; + tBoolean = (arg2, path66, context) => { + if (arg2 instanceof Boolean) + return arg2.valueOf(); + if (typeof arg2 === "boolean") + return arg2; + throw new ValidationError(`${path66}: expected boolean, got ${typeof arg2}`); + }; + tString = (arg2, path66, context) => { + if (arg2 instanceof String) + return arg2.valueOf(); + if (typeof arg2 === "string") + return arg2; + throw new ValidationError(`${path66}: expected string, got ${typeof arg2}`); + }; + tBinary = (arg2, path66, context) => { + if (context.binary === "fromBase64") { + if (arg2 instanceof String) + return Buffer.from(arg2.valueOf(), "base64"); + if (typeof arg2 === "string") + return Buffer.from(arg2, "base64"); + throw new ValidationError(`${path66}: expected base64-encoded buffer, got ${typeof arg2}`); + } + if (context.binary === "toBase64") { + if (!(arg2 instanceof Buffer)) + throw new ValidationError(`${path66}: expected Buffer, got ${typeof arg2}`); + return arg2.toString("base64"); + } + if (context.binary === "buffer") { + if (!(arg2 instanceof Buffer) && !(arg2 instanceof Object)) + throw new ValidationError(`${path66}: expected Buffer, got ${typeof arg2}`); + return arg2; + } + throw new ValidationError(`Unsupported binary behavior "${context.binary}"`); + }; + tAny = (arg2, path66, context) => { + return arg2; + }; + tOptional = (v) => { + return (arg2, path66, context) => { + if (Object.is(arg2, void 0)) + return arg2; + return v(arg2, path66, context); + }; + }; + tArray = (v) => { + return (arg2, path66, context) => { + if (!Array.isArray(arg2)) + throw new ValidationError(`${path66}: expected array, got ${typeof arg2}`); + return arg2.map((x, index) => v(x, path66 + "[" + index + "]", context)); + }; + }; + tObject = (s) => { + return (arg2, path66, context) => { + if (Object.is(arg2, null)) + throw new ValidationError(`${path66}: expected object, got null`); + if (typeof arg2 !== "object") + throw new ValidationError(`${path66}: expected object, got ${typeof arg2}`); + const result2 = {}; + for (const [key, v] of Object.entries(s)) { + const value2 = v(arg2[key], path66 ? path66 + "." + key : key, context); + if (!Object.is(value2, void 0)) + result2[key] = value2; + } + if (context.isUnderTest()) { + for (const [key, value2] of Object.entries(arg2)) { + if (key.startsWith("__testHook")) + result2[key] = value2; + } + } + return result2; + }; + }; + tEnum = (e) => { + return (arg2, path66, context) => { + if (!e.includes(arg2)) + throw new ValidationError(`${path66}: expected one of (${e.join("|")})`); + return arg2; + }; + }; + tChannel = (names) => { + return (arg2, path66, context) => { + return context.tChannelImpl(names, arg2, path66, context); + }; + }; + tType = (name) => { + return (arg2, path66, context) => { + const v = scheme[name]; + if (!v) + throw new ValidationError(path66 + ': unknown type "' + name + '"'); + return v(arg2, path66, context); + }; + }; + } +}); + +// packages/protocol/src/validator.ts +var init_validator = __esm({ + "packages/protocol/src/validator.ts"() { + "use strict"; + init_validatorPrimitives(); + init_validatorPrimitives(); + scheme.AndroidInitializer = tOptional(tObject({})); + scheme.AndroidDevicesParams = tObject({ + host: tOptional(tString), + port: tOptional(tInt), + omitDriverInstall: tOptional(tBoolean) + }); + scheme.AndroidDevicesResult = tObject({ + devices: tArray(tChannel(["AndroidDevice"])) + }); + scheme.AndroidSocketInitializer = tOptional(tObject({})); + scheme.AndroidSocketDataEvent = tObject({ + data: tBinary + }); + scheme.AndroidSocketCloseEvent = tOptional(tObject({})); + scheme.AndroidSocketWriteParams = tObject({ + data: tBinary + }); + scheme.AndroidSocketWriteResult = tOptional(tObject({})); + scheme.AndroidSocketCloseParams = tOptional(tObject({})); + scheme.AndroidSocketCloseResult = tOptional(tObject({})); + scheme.AndroidDeviceInitializer = tObject({ + model: tString, + serial: tString + }); + scheme.AndroidDeviceCloseEvent = tOptional(tObject({})); + scheme.AndroidDeviceWebViewAddedEvent = tObject({ + webView: tType("AndroidWebView") + }); + scheme.AndroidDeviceWebViewRemovedEvent = tObject({ + socketName: tString + }); + scheme.AndroidDeviceWaitParams = tObject({ + androidSelector: tType("AndroidSelector"), + state: tOptional(tEnum(["gone"])) + }); + scheme.AndroidDeviceWaitResult = tOptional(tObject({})); + scheme.AndroidDeviceFillParams = tObject({ + androidSelector: tType("AndroidSelector"), + text: tString + }); + scheme.AndroidDeviceFillResult = tOptional(tObject({})); + scheme.AndroidDeviceTapParams = tObject({ + androidSelector: tType("AndroidSelector"), + duration: tOptional(tFloat) + }); + scheme.AndroidDeviceTapResult = tOptional(tObject({})); + scheme.AndroidDeviceDragParams = tObject({ + androidSelector: tType("AndroidSelector"), + dest: tType("Point"), + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceDragResult = tOptional(tObject({})); + scheme.AndroidDeviceFlingParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceFlingResult = tOptional(tObject({})); + scheme.AndroidDeviceLongTapParams = tObject({ + androidSelector: tType("AndroidSelector") + }); + scheme.AndroidDeviceLongTapResult = tOptional(tObject({})); + scheme.AndroidDevicePinchCloseParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDevicePinchCloseResult = tOptional(tObject({})); + scheme.AndroidDevicePinchOpenParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDevicePinchOpenResult = tOptional(tObject({})); + scheme.AndroidDeviceScrollParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceScrollResult = tOptional(tObject({})); + scheme.AndroidDeviceSwipeParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceSwipeResult = tOptional(tObject({})); + scheme.AndroidDeviceInfoParams = tObject({ + androidSelector: tType("AndroidSelector") + }); + scheme.AndroidDeviceInfoResult = tObject({ + info: tType("AndroidElementInfo") + }); + scheme.AndroidDeviceScreenshotParams = tOptional(tObject({})); + scheme.AndroidDeviceScreenshotResult = tObject({ + binary: tBinary + }); + scheme.AndroidDeviceInputTypeParams = tObject({ + text: tString + }); + scheme.AndroidDeviceInputTypeResult = tOptional(tObject({})); + scheme.AndroidDeviceInputPressParams = tObject({ + key: tString + }); + scheme.AndroidDeviceInputPressResult = tOptional(tObject({})); + scheme.AndroidDeviceInputTapParams = tObject({ + point: tType("Point") + }); + scheme.AndroidDeviceInputTapResult = tOptional(tObject({})); + scheme.AndroidDeviceInputSwipeParams = tObject({ + segments: tArray(tType("Point")), + steps: tInt + }); + scheme.AndroidDeviceInputSwipeResult = tOptional(tObject({})); + scheme.AndroidDeviceInputDragParams = tObject({ + from: tType("Point"), + to: tType("Point"), + steps: tInt + }); + scheme.AndroidDeviceInputDragResult = tOptional(tObject({})); + scheme.AndroidDeviceLaunchBrowserParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + pkg: tOptional(tString), + args: tOptional(tArray(tString)), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })) + }); + scheme.AndroidDeviceLaunchBrowserResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.AndroidDeviceOpenParams = tObject({ + command: tString + }); + scheme.AndroidDeviceOpenResult = tObject({ + socket: tChannel(["AndroidSocket"]) + }); + scheme.AndroidDeviceShellParams = tObject({ + command: tString + }); + scheme.AndroidDeviceShellResult = tObject({ + result: tBinary + }); + scheme.AndroidDeviceInstallApkParams = tObject({ + file: tBinary, + args: tOptional(tArray(tString)) + }); + scheme.AndroidDeviceInstallApkResult = tOptional(tObject({})); + scheme.AndroidDevicePushParams = tObject({ + file: tBinary, + path: tString, + mode: tOptional(tInt) + }); + scheme.AndroidDevicePushResult = tOptional(tObject({})); + scheme.AndroidDeviceConnectToWebViewParams = tObject({ + socketName: tString + }); + scheme.AndroidDeviceConnectToWebViewResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.AndroidDeviceCloseParams = tOptional(tObject({})); + scheme.AndroidDeviceCloseResult = tOptional(tObject({})); + scheme.AndroidWebView = tObject({ + pid: tInt, + pkg: tString, + socketName: tString + }); + scheme.AndroidSelector = tObject({ + checkable: tOptional(tBoolean), + checked: tOptional(tBoolean), + clazz: tOptional(tString), + clickable: tOptional(tBoolean), + depth: tOptional(tInt), + desc: tOptional(tString), + enabled: tOptional(tBoolean), + focusable: tOptional(tBoolean), + focused: tOptional(tBoolean), + hasChild: tOptional(tObject({ + androidSelector: tType("AndroidSelector") + })), + hasDescendant: tOptional(tObject({ + androidSelector: tType("AndroidSelector"), + maxDepth: tOptional(tInt) + })), + longClickable: tOptional(tBoolean), + pkg: tOptional(tString), + res: tOptional(tString), + scrollable: tOptional(tBoolean), + selected: tOptional(tBoolean), + text: tOptional(tString) + }); + scheme.AndroidElementInfo = tObject({ + children: tOptional(tArray(tType("AndroidElementInfo"))), + clazz: tString, + desc: tString, + res: tString, + pkg: tString, + text: tString, + bounds: tType("Rect"), + checkable: tBoolean, + checked: tBoolean, + clickable: tBoolean, + enabled: tBoolean, + focusable: tBoolean, + focused: tBoolean, + longClickable: tBoolean, + scrollable: tBoolean, + selected: tBoolean + }); + scheme.APIRequestContextInitializer = tObject({ + tracing: tChannel(["Tracing"]) + }); + scheme.APIRequestContextFetchParams = tObject({ + url: tString, + encodedParams: tOptional(tString), + params: tOptional(tArray(tType("NameValue"))), + method: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + postData: tOptional(tBinary), + jsonData: tOptional(tString), + formData: tOptional(tArray(tType("NameValue"))), + multipartData: tOptional(tArray(tType("FormField"))), + failOnStatusCode: tOptional(tBoolean), + ignoreHTTPSErrors: tOptional(tBoolean), + maxRedirects: tOptional(tInt), + maxRetries: tOptional(tInt) + }); + scheme.APIRequestContextFetchResult = tObject({ + response: tType("APIResponse") + }); + scheme.APIRequestContextFetchResponseBodyParams = tObject({ + fetchUid: tString + }); + scheme.APIRequestContextFetchResponseBodyResult = tObject({ + binary: tOptional(tBinary) + }); + scheme.APIRequestContextFetchLogParams = tObject({ + fetchUid: tString + }); + scheme.APIRequestContextFetchLogResult = tObject({ + log: tArray(tString) + }); + scheme.APIRequestContextAddCookiesParams = tObject({ + cookies: tArray(tType("SetNetworkCookie")) + }); + scheme.APIRequestContextAddCookiesResult = tOptional(tObject({})); + scheme.APIRequestContextClearCookiesParams = tObject({ + name: tOptional(tString), + nameRegexSource: tOptional(tString), + nameRegexFlags: tOptional(tString), + domain: tOptional(tString), + domainRegexSource: tOptional(tString), + domainRegexFlags: tOptional(tString), + path: tOptional(tString), + pathRegexSource: tOptional(tString), + pathRegexFlags: tOptional(tString) + }); + scheme.APIRequestContextClearCookiesResult = tOptional(tObject({})); + scheme.APIRequestContextCookiesParams = tObject({ + urls: tArray(tString) + }); + scheme.APIRequestContextCookiesResult = tObject({ + cookies: tArray(tType("NetworkCookie")) + }); + scheme.APIRequestContextStorageStateParams = tObject({ + indexedDB: tOptional(tBoolean), + opfs: tOptional(tBoolean) + }); + scheme.APIRequestContextStorageStateResult = tObject({ + cookies: tArray(tType("NetworkCookie")), + origins: tArray(tType("OriginStorage")) + }); + scheme.APIRequestContextDisposeAPIResponseParams = tObject({ + fetchUid: tString + }); + scheme.APIRequestContextDisposeAPIResponseResult = tOptional(tObject({})); + scheme.APIRequestContextDisposeParams = tObject({ + reason: tOptional(tString) + }); + scheme.APIRequestContextDisposeResult = tOptional(tObject({})); + scheme.APIResponse = tObject({ + fetchUid: tString, + url: tString, + status: tInt, + statusText: tString, + headers: tArray(tType("NameValue")), + securityDetails: tOptional(tType("SecurityDetails")), + serverAddr: tOptional(tType("RemoteAddr")), + timing: tOptional(tType("ResourceTiming")), + responseEndTiming: tOptional(tFloat) + }); + scheme.ArtifactInitializer = tObject({ + absolutePath: tString + }); + scheme.ArtifactPathAfterFinishedParams = tOptional(tObject({})); + scheme.ArtifactPathAfterFinishedResult = tObject({ + value: tString + }); + scheme.ArtifactSaveAsParams = tObject({ + path: tString + }); + scheme.ArtifactSaveAsResult = tOptional(tObject({})); + scheme.ArtifactSaveAsStreamParams = tOptional(tObject({})); + scheme.ArtifactSaveAsStreamResult = tObject({ + stream: tChannel(["Stream"]) + }); + scheme.ArtifactFailureParams = tOptional(tObject({})); + scheme.ArtifactFailureResult = tObject({ + error: tOptional(tString) + }); + scheme.ArtifactStreamParams = tOptional(tObject({})); + scheme.ArtifactStreamResult = tObject({ + stream: tChannel(["Stream"]) + }); + scheme.ArtifactCancelParams = tOptional(tObject({})); + scheme.ArtifactCancelResult = tOptional(tObject({})); + scheme.ArtifactDeleteParams = tOptional(tObject({})); + scheme.ArtifactDeleteResult = tOptional(tObject({})); + scheme.StreamInitializer = tOptional(tObject({})); + scheme.StreamReadParams = tObject({ + size: tOptional(tInt) + }); + scheme.StreamReadResult = tObject({ + binary: tBinary + }); + scheme.StreamCloseParams = tOptional(tObject({})); + scheme.StreamCloseResult = tOptional(tObject({})); + scheme.WritableStreamInitializer = tOptional(tObject({})); + scheme.WritableStreamWriteParams = tObject({ + binary: tBinary + }); + scheme.WritableStreamWriteResult = tOptional(tObject({})); + scheme.WritableStreamCloseParams = tOptional(tObject({})); + scheme.WritableStreamCloseResult = tOptional(tObject({})); + scheme.BrowserInitializer = tObject({ + version: tString, + name: tString, + browserName: tEnum(["chromium", "firefox", "webkit"]) + }); + scheme.BrowserContextEvent = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserCloseEvent = tOptional(tObject({})); + scheme.BrowserStartServerParams = tObject({ + title: tString, + workspaceDir: tOptional(tString), + metadata: tOptional(tAny), + host: tOptional(tString), + port: tOptional(tInt) + }); + scheme.BrowserStartServerResult = tObject({ + endpoint: tString + }); + scheme.BrowserStopServerParams = tOptional(tObject({})); + scheme.BrowserStopServerResult = tOptional(tObject({})); + scheme.BrowserCloseParams = tObject({ + reason: tOptional(tString) + }); + scheme.BrowserCloseResult = tOptional(tObject({})); + scheme.BrowserKillForTestsParams = tOptional(tObject({})); + scheme.BrowserKillForTestsResult = tOptional(tObject({})); + scheme.BrowserDefaultUserAgentForTestParams = tOptional(tObject({})); + scheme.BrowserDefaultUserAgentForTestResult = tObject({ + userAgent: tString + }); + scheme.BrowserNewContextParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))), + credentials: tOptional(tArray(tType("SetVirtualCredential"))) + })) + }); + scheme.BrowserNewContextResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserNewContextForReuseParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))), + credentials: tOptional(tArray(tType("SetVirtualCredential"))) + })) + }); + scheme.BrowserNewContextForReuseResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserDisconnectFromReusedContextParams = tObject({ + reason: tString + }); + scheme.BrowserDisconnectFromReusedContextResult = tOptional(tObject({})); + scheme.BrowserNewBrowserCDPSessionParams = tOptional(tObject({})); + scheme.BrowserNewBrowserCDPSessionResult = tObject({ + session: tChannel(["CDPSession"]) + }); + scheme.BrowserStartTracingParams = tObject({ + page: tOptional(tChannel(["Page"])), + screenshots: tOptional(tBoolean), + categories: tOptional(tArray(tString)) + }); + scheme.BrowserStartTracingResult = tOptional(tObject({})); + scheme.BrowserStopTracingParams = tOptional(tObject({})); + scheme.BrowserStopTracingResult = tObject({ + artifact: tChannel(["Artifact"]) + }); + scheme.BrowserContextInitializer = tObject({ + debugger: tChannel(["Debugger"]), + requestContext: tChannel(["APIRequestContext"]), + tracing: tChannel(["Tracing"]), + options: tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString) + }) + }); + scheme.BrowserContextBindingCallEvent = tObject({ + binding: tChannel(["BindingCall"]) + }); + scheme.BrowserContextConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat, + page: tOptional(tChannel(["Page"])), + worker: tOptional(tChannel(["Worker"])) + }); + scheme.BrowserContextCloseEvent = tOptional(tObject({})); + scheme.BrowserContextDialogEvent = tObject({ + dialog: tChannel(["Dialog"]) + }); + scheme.BrowserContextDialogClosedEvent = tObject({ + dialog: tChannel(["Dialog"]) + }); + scheme.BrowserContextPageEvent = tObject({ + page: tChannel(["Page"]) + }); + scheme.BrowserContextPageErrorEvent = tObject({ + error: tType("SerializedError"), + page: tChannel(["Page"]), + location: tObject({ + url: tString, + line: tInt, + column: tInt + }) + }); + scheme.BrowserContextRouteEvent = tObject({ + route: tChannel(["Route"]) + }); + scheme.BrowserContextWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) + }); + scheme.BrowserContextServiceWorkerEvent = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.BrowserContextRequestEvent = tObject({ + request: tChannel(["Request"]), + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRequestFailedEvent = tObject({ + request: tChannel(["Request"]), + failureText: tOptional(tString), + responseEndTiming: tFloat, + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRequestFinishedEvent = tObject({ + request: tChannel(["Request"]), + response: tOptional(tChannel(["Response"])), + responseEndTiming: tFloat, + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextResponseEvent = tObject({ + response: tChannel(["Response"]), + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRecorderEventEvent = tObject({ + event: tEnum(["actionAdded", "actionUpdated", "signalAdded"]), + data: tAny, + page: tChannel(["Page"]), + code: tString + }); + scheme.BrowserContextAddCookiesParams = tObject({ + cookies: tArray(tType("SetNetworkCookie")) + }); + scheme.BrowserContextAddCookiesResult = tOptional(tObject({})); + scheme.BrowserContextAddInitScriptParams = tObject({ + source: tString + }); + scheme.BrowserContextAddInitScriptResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.BrowserContextClearCookiesParams = tObject({ + name: tOptional(tString), + nameRegexSource: tOptional(tString), + nameRegexFlags: tOptional(tString), + domain: tOptional(tString), + domainRegexSource: tOptional(tString), + domainRegexFlags: tOptional(tString), + path: tOptional(tString), + pathRegexSource: tOptional(tString), + pathRegexFlags: tOptional(tString) + }); + scheme.BrowserContextClearCookiesResult = tOptional(tObject({})); + scheme.BrowserContextClearPermissionsParams = tOptional(tObject({})); + scheme.BrowserContextClearPermissionsResult = tOptional(tObject({})); + scheme.BrowserContextCloseParams = tObject({ + reason: tOptional(tString) + }); + scheme.BrowserContextCloseResult = tOptional(tObject({})); + scheme.BrowserContextCookiesParams = tObject({ + urls: tArray(tString) + }); + scheme.BrowserContextCookiesResult = tObject({ + cookies: tArray(tType("NetworkCookie")) + }); + scheme.BrowserContextExposeBindingParams = tObject({ + name: tString, + noGlobal: tOptional(tBoolean) + }); + scheme.BrowserContextExposeBindingResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.BrowserContextGrantPermissionsParams = tObject({ + permissions: tArray(tString), + origin: tOptional(tString) + }); + scheme.BrowserContextGrantPermissionsResult = tOptional(tObject({})); + scheme.BrowserContextNewPageParams = tOptional(tObject({})); + scheme.BrowserContextNewPageResult = tObject({ + page: tChannel(["Page"]) + }); + scheme.BrowserContextRegisterSelectorEngineParams = tObject({ + selectorEngine: tType("SelectorEngine") + }); + scheme.BrowserContextRegisterSelectorEngineResult = tOptional(tObject({})); + scheme.BrowserContextSetTestIdAttributeNameParams = tObject({ + testIdAttributeName: tString + }); + scheme.BrowserContextSetTestIdAttributeNameResult = tOptional(tObject({})); + scheme.BrowserContextSetExtraHTTPHeadersParams = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.BrowserContextSetExtraHTTPHeadersResult = tOptional(tObject({})); + scheme.BrowserContextSetGeolocationParams = tObject({ + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })) + }); + scheme.BrowserContextSetGeolocationResult = tOptional(tObject({})); + scheme.BrowserContextSetHTTPCredentialsParams = tObject({ + httpCredentials: tOptional(tArray(tType("HttpCredentials"))) + }); + scheme.BrowserContextSetHTTPCredentialsResult = tOptional(tObject({})); + scheme.BrowserContextSetNetworkInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.BrowserContextSetNetworkInterceptionPatternsResult = tOptional(tObject({})); + scheme.BrowserContextSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.BrowserContextSetWebSocketInterceptionPatternsResult = tOptional(tObject({})); + scheme.BrowserContextSetOfflineParams = tObject({ + offline: tBoolean + }); + scheme.BrowserContextSetOfflineResult = tOptional(tObject({})); + scheme.BrowserContextStorageStateParams = tObject({ + indexedDB: tOptional(tBoolean), + opfs: tOptional(tBoolean), + credentials: tOptional(tBoolean) + }); + scheme.BrowserContextStorageStateResult = tObject({ + cookies: tArray(tType("NetworkCookie")), + origins: tArray(tType("OriginStorage")), + credentials: tOptional(tArray(tType("VirtualCredential"))) + }); + scheme.BrowserContextSetStorageStateParams = tObject({ + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))), + credentials: tOptional(tArray(tType("SetVirtualCredential"))) + })) + }); + scheme.BrowserContextSetStorageStateResult = tOptional(tObject({})); + scheme.BrowserContextPauseParams = tOptional(tObject({})); + scheme.BrowserContextPauseResult = tOptional(tObject({})); + scheme.BrowserContextShowRecorderParams = tObject({ + language: tOptional(tString), + mode: tOptional(tEnum(["inspecting", "recording"])), + pauseOnNextStatement: tOptional(tBoolean), + testIdAttributeName: tOptional(tString), + launchOptions: tOptional(tAny), + contextOptions: tOptional(tAny), + device: tOptional(tString), + saveStorage: tOptional(tString), + outputFile: tOptional(tString), + handleSIGINT: tOptional(tBoolean), + omitCallTracking: tOptional(tBoolean) + }); + scheme.BrowserContextShowRecorderResult = tOptional(tObject({})); + scheme.BrowserContextStartRecordingParams = tObject({ + language: tOptional(tString) + }); + scheme.BrowserContextStartRecordingResult = tOptional(tObject({})); + scheme.BrowserContextStopRecordingParams = tOptional(tObject({})); + scheme.BrowserContextStopRecordingResult = tOptional(tObject({})); + scheme.BrowserContextExposeConsoleApiParams = tOptional(tObject({})); + scheme.BrowserContextExposeConsoleApiResult = tOptional(tObject({})); + scheme.BrowserContextNewCDPSessionParams = tObject({ + page: tOptional(tChannel(["Page"])), + frame: tOptional(tChannel(["Frame"])) + }); + scheme.BrowserContextNewCDPSessionResult = tObject({ + session: tChannel(["CDPSession"]) + }); + scheme.BrowserContextCreateTempFilesParams = tObject({ + rootDirName: tOptional(tString), + items: tArray(tObject({ + name: tString, + lastModifiedMs: tOptional(tFloat) + })) + }); + scheme.BrowserContextCreateTempFilesResult = tObject({ + rootDir: tOptional(tChannel(["WritableStream"])), + writableStreams: tArray(tChannel(["WritableStream"])) + }); + scheme.BrowserContextUpdateSubscriptionParams = tObject({ + event: tEnum(["console", "dialog", "dialogClosed", "request", "response", "requestFinished", "requestFailed"]), + enabled: tBoolean + }); + scheme.BrowserContextUpdateSubscriptionResult = tOptional(tObject({})); + scheme.BrowserContextClockFastForwardParams = tObject({ + ticksNumber: tOptional(tFloat), + ticksString: tOptional(tString) + }); + scheme.BrowserContextClockFastForwardResult = tOptional(tObject({})); + scheme.BrowserContextClockInstallParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockInstallResult = tOptional(tObject({})); + scheme.BrowserContextClockPauseAtParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockPauseAtResult = tOptional(tObject({})); + scheme.BrowserContextClockResumeParams = tOptional(tObject({})); + scheme.BrowserContextClockResumeResult = tOptional(tObject({})); + scheme.BrowserContextClockRunForParams = tObject({ + ticksNumber: tOptional(tFloat), + ticksString: tOptional(tString) + }); + scheme.BrowserContextClockRunForResult = tOptional(tObject({})); + scheme.BrowserContextClockSetFixedTimeParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockSetFixedTimeResult = tOptional(tObject({})); + scheme.BrowserContextClockSetSystemTimeParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockSetSystemTimeResult = tOptional(tObject({})); + scheme.BrowserContextCredentialsInstallParams = tOptional(tObject({})); + scheme.BrowserContextCredentialsInstallResult = tOptional(tObject({})); + scheme.BrowserContextCredentialsCreateParams = tObject({ + rpId: tString, + id: tOptional(tString), + userHandle: tOptional(tString), + privateKey: tOptional(tString), + publicKey: tOptional(tString), + signCount: tOptional(tInt) + }); + scheme.BrowserContextCredentialsCreateResult = tObject({ + credential: tType("VirtualCredential") + }); + scheme.BrowserContextCredentialsGetParams = tObject({ + rpId: tOptional(tString), + id: tOptional(tString) + }); + scheme.BrowserContextCredentialsGetResult = tObject({ + credentials: tArray(tType("VirtualCredential")) + }); + scheme.BrowserContextCredentialsDeleteParams = tObject({ + id: tString + }); + scheme.BrowserContextCredentialsDeleteResult = tOptional(tObject({})); + scheme.BrowserTypeInitializer = tObject({ + executablePath: tString, + name: tString + }); + scheme.BrowserTypeLaunchParams = tObject({ + channel: tOptional(tString), + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + ignoreAllDefaultArgs: tOptional(tBoolean), + ignoreDefaultArgs: tOptional(tArray(tString)), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tInt), + slowMo: tOptional(tFloat) + }); + scheme.BrowserTypeLaunchResult = tObject({ + browser: tChannel(["Browser"]) + }); + scheme.BrowserTypeLaunchPersistentContextParams = tObject({ + channel: tOptional(tString), + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + ignoreAllDefaultArgs: tOptional(tBoolean), + ignoreDefaultArgs: tOptional(tArray(tString)), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tInt), + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + userDataDir: tString, + slowMo: tOptional(tFloat) + }); + scheme.BrowserTypeLaunchPersistentContextResult = tObject({ + browser: tChannel(["Browser"]), + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserTypeConnectOverCDPParams = tObject({ + endpointURL: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + slowMo: tOptional(tFloat), + isLocal: tOptional(tBoolean), + noDefaults: tOptional(tBoolean), + isWebView: tOptional(tBoolean), + artifactsDir: tOptional(tString), + transport: tOptional(tBinary) + }); + scheme.BrowserTypeConnectOverCDPResult = tObject({ + browser: tChannel(["Browser"]), + defaultContext: tOptional(tChannel(["BrowserContext"])) + }); + scheme.BrowserTypeConnectToWorkerParams = tObject({ + endpoint: tString + }); + scheme.BrowserTypeConnectToWorkerResult = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.Metadata = tObject({ + location: tOptional(tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + })), + title: tOptional(tString), + internal: tOptional(tBoolean), + timeout: tOptional(tFloat) + }); + scheme.ClientSideCallMetadata = tObject({ + id: tString, + stack: tOptional(tArray(tType("StackFrame"))) + }); + scheme.SDKLanguage = tEnum(["javascript", "python", "java", "csharp"]); + scheme.DisposableInitializer = tOptional(tObject({})); + scheme.DisposableDisposeParams = tOptional(tObject({})); + scheme.DisposableDisposeResult = tOptional(tObject({})); + scheme.WaitInfo = tObject({ + waitId: tString, + phase: tEnum(["before", "after", "log"]), + event: tOptional(tString), + message: tOptional(tString), + error: tOptional(tString) + }); + scheme.ElectronInitializer = tOptional(tObject({})); + scheme.ElectronLaunchParams = tObject({ + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + chromiumSandbox: tOptional(tBoolean), + cwd: tOptional(tString), + env: tOptional(tArray(tType("NameValue"))), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + bypassCSP: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + ignoreHTTPSErrors: tOptional(tBoolean), + locale: tOptional(tString), + offline: tOptional(tBoolean), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + timezoneId: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString) + }); + scheme.ElectronLaunchResult = tObject({ + electronApplication: tChannel(["ElectronApplication"]) + }); + scheme.ElectronApplicationInitializer = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.ElectronApplicationCloseEvent = tOptional(tObject({})); + scheme.ElectronApplicationConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + }); + scheme.ElectronApplicationBrowserWindowParams = tObject({ + page: tChannel(["Page"]) + }); + scheme.ElectronApplicationBrowserWindowResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElectronApplicationEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElectronApplicationEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElectronApplicationEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElectronApplicationEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElectronApplicationUpdateSubscriptionParams = tObject({ + event: tEnum(["console"]), + enabled: tBoolean + }); + scheme.ElectronApplicationUpdateSubscriptionResult = tOptional(tObject({})); + scheme.FrameInitializer = tObject({ + url: tString, + name: tString, + parentFrame: tOptional(tChannel(["Frame"])), + loadStates: tArray(tType("LifecycleEvent")) + }); + scheme.FrameLoadstateEvent = tObject({ + add: tOptional(tType("LifecycleEvent")), + remove: tOptional(tType("LifecycleEvent")) + }); + scheme.FrameNavigatedEvent = tObject({ + url: tString, + name: tString, + newDocument: tOptional(tObject({ + request: tOptional(tChannel(["Request"])) + })), + error: tOptional(tString) + }); + scheme.FrameEvalOnSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvalOnSelectorResult = tObject({ + value: tType("SerializedValue") + }); + scheme.FrameEvalOnSelectorAllParams = tObject({ + selector: tString, + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvalOnSelectorAllResult = tObject({ + value: tType("SerializedValue") + }); + scheme.FrameAddScriptTagParams = tObject({ + url: tOptional(tString), + content: tOptional(tString), + type: tOptional(tString) + }); + scheme.FrameAddScriptTagResult = tObject({ + element: tChannel(["ElementHandle"]) + }); + scheme.FrameAddStyleTagParams = tObject({ + url: tOptional(tString), + content: tOptional(tString) + }); + scheme.FrameAddStyleTagResult = tObject({ + element: tChannel(["ElementHandle"]) + }); + scheme.FrameAriaSnapshotParams = tObject({ + mode: tOptional(tEnum(["ai", "default"])), + selector: tOptional(tString), + depth: tOptional(tInt), + boxes: tOptional(tBoolean) + }); + scheme.FrameAriaSnapshotResult = tObject({ + snapshot: tString + }); + scheme.FrameAriaSnapshotJSONParams = tObject({ + mode: tOptional(tEnum(["ai", "default"])), + selector: tOptional(tString), + depth: tOptional(tInt), + boxes: tOptional(tBoolean) + }); + scheme.FrameAriaSnapshotJSONResult = tObject({ + snapshot: tAny + }); + scheme.FrameBlurParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameBlurResult = tOptional(tObject({})); + scheme.FrameCheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameCheckResult = tOptional(tObject({})); + scheme.FrameClickParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + noWaitAfter: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameClickResult = tOptional(tObject({})); + scheme.FrameContentParams = tObject({ + includeShadow: tOptional(tBoolean) + }); + scheme.FrameContentResult = tObject({ + value: tString + }); + scheme.FrameDragAndDropParams = tObject({ + source: tString, + target: tString, + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + trial: tOptional(tBoolean), + sourcePosition: tOptional(tType("Point")), + targetPosition: tOptional(tType("Point")), + strict: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameDragAndDropResult = tOptional(tObject({})); + scheme.FrameDropParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + position: tOptional(tType("Point")), + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))), + data: tOptional(tArray(tObject({ + mimeType: tString, + value: tString + }))) + }); + scheme.FrameDropResult = tOptional(tObject({})); + scheme.FrameDblclickParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameDblclickResult = tOptional(tObject({})); + scheme.FrameDispatchEventParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + type: tString, + eventInit: tType("SerializedArgument") + }); + scheme.FrameDispatchEventResult = tOptional(tObject({})); + scheme.FrameEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.FrameEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.FrameFillParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + value: tString, + force: tOptional(tBoolean) + }); + scheme.FrameFillResult = tOptional(tObject({})); + scheme.FrameFocusParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameFocusResult = tOptional(tObject({})); + scheme.FrameFrameElementParams = tOptional(tObject({})); + scheme.FrameFrameElementResult = tObject({ + element: tChannel(["ElementHandle"]) + }); + scheme.FrameResolveSelectorParams = tObject({ + selector: tString, + sdkLanguage: tOptional(tType("SDKLanguage")) + }); + scheme.FrameResolveSelectorResult = tObject({ + resolvedSelector: tString, + locatorCode: tOptional(tString) + }); + scheme.FrameHighlightParams = tObject({ + selector: tString, + style: tOptional(tString) + }); + scheme.FrameHighlightResult = tOptional(tObject({})); + scheme.FrameHideHighlightParams = tObject({ + selector: tString + }); + scheme.FrameHideHighlightResult = tOptional(tObject({})); + scheme.FrameGetAttributeParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + name: tString + }); + scheme.FrameGetAttributeResult = tObject({ + value: tOptional(tString) + }); + scheme.FrameGotoParams = tObject({ + url: tString, + waitUntil: tOptional(tType("LifecycleEvent")), + referer: tOptional(tString) + }); + scheme.FrameGotoResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.FrameHoverParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameHoverResult = tOptional(tObject({})); + scheme.FrameInnerHTMLParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameInnerHTMLResult = tObject({ + value: tString + }); + scheme.FrameInnerTextParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameInnerTextResult = tObject({ + value: tString + }); + scheme.FrameInputValueParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameInputValueResult = tObject({ + value: tString + }); + scheme.FrameIsCheckedParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsCheckedResult = tObject({ + value: tBoolean + }); + scheme.FrameIsDisabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsDisabledResult = tObject({ + value: tBoolean + }); + scheme.FrameIsEnabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsEnabledResult = tObject({ + value: tBoolean + }); + scheme.FrameIsHiddenParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsHiddenResult = tObject({ + value: tBoolean + }); + scheme.FrameIsVisibleParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsVisibleResult = tObject({ + value: tBoolean + }); + scheme.FrameIsEditableParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsEditableResult = tObject({ + value: tBoolean + }); + scheme.FramePressParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + key: tString, + delay: tOptional(tFloat), + noWaitAfter: tOptional(tBoolean) + }); + scheme.FramePressResult = tOptional(tObject({})); + scheme.FrameQuerySelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameQuerySelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.FrameQuerySelectorAllParams = tObject({ + selector: tString + }); + scheme.FrameQuerySelectorAllResult = tObject({ + elements: tArray(tChannel(["ElementHandle"])) + }); + scheme.FrameQueryCountParams = tObject({ + selector: tString + }); + scheme.FrameQueryCountResult = tObject({ + value: tInt + }); + scheme.FrameSelectOptionParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + elements: tOptional(tArray(tChannel(["ElementHandle"]))), + options: tOptional(tArray(tObject({ + valueOrLabel: tOptional(tString), + value: tOptional(tString), + label: tOptional(tString), + index: tOptional(tInt) + }))), + force: tOptional(tBoolean) + }); + scheme.FrameSelectOptionResult = tObject({ + values: tArray(tString) + }); + scheme.FrameSetContentParams = tObject({ + html: tString, + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.FrameSetContentResult = tOptional(tObject({})); + scheme.FrameSetInputFilesParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localDirectory: tOptional(tString), + directoryStream: tOptional(tChannel(["WritableStream"])), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))) + }); + scheme.FrameSetInputFilesResult = tOptional(tObject({})); + scheme.FrameTapParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameTapResult = tOptional(tObject({})); + scheme.FrameTextContentParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameTextContentResult = tObject({ + value: tOptional(tString) + }); + scheme.FrameTitleParams = tOptional(tObject({})); + scheme.FrameTitleResult = tObject({ + value: tString + }); + scheme.FrameTypeParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + text: tString, + delay: tOptional(tFloat) + }); + scheme.FrameTypeResult = tOptional(tObject({})); + scheme.FrameUncheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameUncheckResult = tOptional(tObject({})); + scheme.FrameWaitForTimeoutParams = tObject({ + waitTimeout: tFloat + }); + scheme.FrameWaitForTimeoutResult = tOptional(tObject({})); + scheme.FrameWaitForFunctionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument"), + pollingInterval: tOptional(tFloat), + selector: tOptional(tString), + strict: tOptional(tBoolean) + }); + scheme.FrameWaitForFunctionResult = tObject({ + handle: tOptional(tChannel(["ElementHandle", "JSHandle"])) + }); + scheme.FrameWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])), + omitReturnValue: tOptional(tBoolean) + }); + scheme.FrameWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.FrameExpectParams = tObject({ + selector: tOptional(tString), + expression: tString, + expressionArg: tOptional(tAny), + pseudo: tOptional(tEnum(["before", "after"])), + expectedText: tOptional(tArray(tType("ExpectedTextValue"))), + expectedNumber: tOptional(tFloat), + expectedValue: tOptional(tType("SerializedArgument")), + useInnerText: tOptional(tBoolean), + isNot: tBoolean + }); + scheme.FrameExpectResult = tOptional(tObject({})); + scheme.FrameExpectErrorDetails = tObject({ + received: tOptional(tObject({ + value: tOptional(tType("SerializedValue")), + ariaSnapshot: tOptional(tString) + })), + timedOut: tOptional(tBoolean), + customErrorMessage: tOptional(tString) + }); + scheme.FrameWebmcpToolsParams = tOptional(tObject({})); + scheme.FrameWebmcpToolsResult = tObject({ + tools: tArray(tObject({ + name: tString, + description: tString, + inputSchema: tOptional(tAny), + annotations: tOptional(tObject({ + readOnly: tOptional(tBoolean), + untrustedContent: tOptional(tBoolean), + consequential: tOptional(tBoolean) + })) + })) + }); + scheme.FrameWebmcpCallToolParams = tObject({ + name: tString, + input: tType("SerializedArgument") + }); + scheme.FrameWebmcpCallToolResult = tObject({ + result: tType("SerializedValue") + }); + scheme.JSHandleInitializer = tObject({ + preview: tString + }); + scheme.JSHandlePreviewUpdatedEvent = tObject({ + preview: tString + }); + scheme.ElementHandlePreviewUpdatedEvent = tType("JSHandlePreviewUpdatedEvent"); + scheme.JSHandleDisposeParams = tOptional(tObject({})); + scheme.ElementHandleDisposeParams = tType("JSHandleDisposeParams"); + scheme.JSHandleDisposeResult = tOptional(tObject({})); + scheme.ElementHandleDisposeResult = tType("JSHandleDisposeResult"); + scheme.JSHandleEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvaluateExpressionParams = tType("JSHandleEvaluateExpressionParams"); + scheme.JSHandleEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleEvaluateExpressionResult = tType("JSHandleEvaluateExpressionResult"); + scheme.JSHandleEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvaluateExpressionHandleParams = tType("JSHandleEvaluateExpressionHandleParams"); + scheme.JSHandleEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElementHandleEvaluateExpressionHandleResult = tType("JSHandleEvaluateExpressionHandleResult"); + scheme.JSHandleGetPropertyListParams = tOptional(tObject({})); + scheme.ElementHandleGetPropertyListParams = tType("JSHandleGetPropertyListParams"); + scheme.JSHandleGetPropertyListResult = tObject({ + properties: tArray(tObject({ + name: tString, + value: tChannel(["ElementHandle", "JSHandle"]) + })) + }); + scheme.ElementHandleGetPropertyListResult = tType("JSHandleGetPropertyListResult"); + scheme.JSHandleGetPropertyParams = tObject({ + name: tString + }); + scheme.ElementHandleGetPropertyParams = tType("JSHandleGetPropertyParams"); + scheme.JSHandleGetPropertyResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElementHandleGetPropertyResult = tType("JSHandleGetPropertyResult"); + scheme.JSHandleJsonValueParams = tOptional(tObject({})); + scheme.ElementHandleJsonValueParams = tType("JSHandleJsonValueParams"); + scheme.JSHandleJsonValueResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleJsonValueResult = tType("JSHandleJsonValueResult"); + scheme.ElementHandleInitializer = tObject({ + preview: tString + }); + scheme.ElementHandleEvalOnSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvalOnSelectorResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleEvalOnSelectorAllParams = tObject({ + selector: tString, + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvalOnSelectorAllResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleBoundingBoxParams = tOptional(tObject({})); + scheme.ElementHandleBoundingBoxResult = tObject({ + value: tOptional(tType("Rect")) + }); + scheme.ElementHandleCheckParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleCheckResult = tOptional(tObject({})); + scheme.ElementHandleClickParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + noWaitAfter: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.ElementHandleClickResult = tOptional(tObject({})); + scheme.ElementHandleContentFrameParams = tOptional(tObject({})); + scheme.ElementHandleContentFrameResult = tObject({ + frame: tOptional(tChannel(["Frame"])) + }); + scheme.ElementHandleDblclickParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.ElementHandleDblclickResult = tOptional(tObject({})); + scheme.ElementHandleDispatchEventParams = tObject({ + type: tString, + eventInit: tType("SerializedArgument") + }); + scheme.ElementHandleDispatchEventResult = tOptional(tObject({})); + scheme.ElementHandleFillParams = tObject({ + value: tString, + force: tOptional(tBoolean) + }); + scheme.ElementHandleFillResult = tOptional(tObject({})); + scheme.ElementHandleFocusParams = tOptional(tObject({})); + scheme.ElementHandleFocusResult = tOptional(tObject({})); + scheme.ElementHandleGetAttributeParams = tObject({ + name: tString + }); + scheme.ElementHandleGetAttributeResult = tObject({ + value: tOptional(tString) + }); + scheme.ElementHandleHoverParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleHoverResult = tOptional(tObject({})); + scheme.ElementHandleInnerHTMLParams = tOptional(tObject({})); + scheme.ElementHandleInnerHTMLResult = tObject({ + value: tString + }); + scheme.ElementHandleInnerTextParams = tOptional(tObject({})); + scheme.ElementHandleInnerTextResult = tObject({ + value: tString + }); + scheme.ElementHandleInputValueParams = tOptional(tObject({})); + scheme.ElementHandleInputValueResult = tObject({ + value: tString + }); + scheme.ElementHandleIsCheckedParams = tOptional(tObject({})); + scheme.ElementHandleIsCheckedResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsDisabledParams = tOptional(tObject({})); + scheme.ElementHandleIsDisabledResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsEditableParams = tOptional(tObject({})); + scheme.ElementHandleIsEditableResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsEnabledParams = tOptional(tObject({})); + scheme.ElementHandleIsEnabledResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsHiddenParams = tOptional(tObject({})); + scheme.ElementHandleIsHiddenResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsVisibleParams = tOptional(tObject({})); + scheme.ElementHandleIsVisibleResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleOwnerFrameParams = tOptional(tObject({})); + scheme.ElementHandleOwnerFrameResult = tObject({ + frame: tOptional(tChannel(["Frame"])) + }); + scheme.ElementHandlePressParams = tObject({ + key: tString, + delay: tOptional(tFloat), + noWaitAfter: tOptional(tBoolean) + }); + scheme.ElementHandlePressResult = tOptional(tObject({})); + scheme.ElementHandleQuerySelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.ElementHandleQuerySelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.ElementHandleQuerySelectorAllParams = tObject({ + selector: tString + }); + scheme.ElementHandleQuerySelectorAllResult = tObject({ + elements: tArray(tChannel(["ElementHandle"])) + }); + scheme.ElementHandleScreenshotParams = tObject({ + type: tOptional(tEnum(["png", "jpeg", "webp"])), + quality: tOptional(tInt), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) + }); + scheme.ElementHandleScreenshotResult = tObject({ + binary: tBinary + }); + scheme.ElementHandleScrollIntoViewIfNeededParams = tOptional(tObject({})); + scheme.ElementHandleScrollIntoViewIfNeededResult = tOptional(tObject({})); + scheme.ElementHandleSelectOptionParams = tObject({ + elements: tOptional(tArray(tChannel(["ElementHandle"]))), + options: tOptional(tArray(tObject({ + valueOrLabel: tOptional(tString), + value: tOptional(tString), + label: tOptional(tString), + index: tOptional(tInt) + }))), + force: tOptional(tBoolean) + }); + scheme.ElementHandleSelectOptionResult = tObject({ + values: tArray(tString) + }); + scheme.ElementHandleSelectTextParams = tObject({ + force: tOptional(tBoolean) + }); + scheme.ElementHandleSelectTextResult = tOptional(tObject({})); + scheme.ElementHandleSetInputFilesParams = tObject({ + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localDirectory: tOptional(tString), + directoryStream: tOptional(tChannel(["WritableStream"])), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))) + }); + scheme.ElementHandleSetInputFilesResult = tOptional(tObject({})); + scheme.ElementHandleTapParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleTapResult = tOptional(tObject({})); + scheme.ElementHandleTextContentParams = tOptional(tObject({})); + scheme.ElementHandleTextContentResult = tObject({ + value: tOptional(tString) + }); + scheme.ElementHandleTypeParams = tObject({ + text: tString, + delay: tOptional(tFloat) + }); + scheme.ElementHandleTypeResult = tOptional(tObject({})); + scheme.ElementHandleUncheckParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleUncheckResult = tOptional(tObject({})); + scheme.ElementHandleWaitForElementStateParams = tObject({ + state: tEnum(["visible", "hidden", "stable", "enabled", "disabled", "editable"]) + }); + scheme.ElementHandleWaitForElementStateResult = tOptional(tObject({})); + scheme.ElementHandleWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])) + }); + scheme.ElementHandleWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.LocalUtilsInitializer = tObject({ + deviceDescriptors: tArray(tObject({ + name: tString, + descriptor: tObject({ + userAgent: tString, + viewport: tObject({ + width: tInt, + height: tInt + }), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + deviceScaleFactor: tFloat, + isMobile: tBoolean, + hasTouch: tBoolean, + defaultBrowserType: tEnum(["chromium", "firefox", "webkit"]) + }) + })) + }); + scheme.LocalUtilsZipParams = tObject({ + zipFile: tString, + entries: tArray(tType("NameValue")), + stacksId: tOptional(tString), + mode: tEnum(["write", "append"]), + includeSources: tBoolean, + additionalSources: tOptional(tArray(tString)) + }); + scheme.LocalUtilsZipResult = tOptional(tObject({})); + scheme.LocalUtilsHarOpenParams = tObject({ + file: tString + }); + scheme.LocalUtilsHarOpenResult = tObject({ + harId: tOptional(tString), + error: tOptional(tString) + }); + scheme.LocalUtilsHarLookupParams = tObject({ + harId: tString, + url: tString, + method: tString, + headers: tArray(tType("NameValue")), + postData: tOptional(tBinary), + isNavigationRequest: tBoolean + }); + scheme.LocalUtilsHarLookupResult = tObject({ + action: tEnum(["error", "redirect", "fulfill", "noentry"]), + message: tOptional(tString), + redirectURL: tOptional(tString), + status: tOptional(tInt), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tBinary) + }); + scheme.LocalUtilsHarCloseParams = tObject({ + harId: tString + }); + scheme.LocalUtilsHarCloseResult = tOptional(tObject({})); + scheme.LocalUtilsHarUnzipParams = tObject({ + zipFile: tString, + harFile: tString, + resourcesDir: tOptional(tString) + }); + scheme.LocalUtilsHarUnzipResult = tOptional(tObject({})); + scheme.LocalUtilsConnectParams = tObject({ + endpoint: tString, + headers: tOptional(tAny), + exposeNetwork: tOptional(tString), + slowMo: tOptional(tFloat), + socksProxyRedirectPortForTest: tOptional(tInt) + }); + scheme.LocalUtilsConnectResult = tObject({ + pipe: tChannel(["JsonPipe"]), + headers: tArray(tType("NameValue")) + }); + scheme.LocalUtilsTracingStartedParams = tObject({ + tracesDir: tOptional(tString), + traceName: tString, + live: tOptional(tBoolean) + }); + scheme.LocalUtilsTracingStartedResult = tObject({ + stacksId: tString + }); + scheme.LocalUtilsAddStackToTracingNoReplyParams = tObject({ + callData: tType("ClientSideCallMetadata") + }); + scheme.LocalUtilsAddStackToTracingNoReplyResult = tOptional(tObject({})); + scheme.LocalUtilsTraceDiscardedParams = tObject({ + stacksId: tString + }); + scheme.LocalUtilsTraceDiscardedResult = tOptional(tObject({})); + scheme.LocalUtilsGlobToRegexParams = tObject({ + glob: tString, + baseURL: tOptional(tString), + webSocketUrl: tOptional(tBoolean) + }); + scheme.LocalUtilsGlobToRegexResult = tObject({ + regex: tString + }); + scheme.LocalUtilsAsLocatorDescriptionParams = tObject({ + selector: tString, + sdkLanguage: tType("SDKLanguage") + }); + scheme.LocalUtilsAsLocatorDescriptionResult = tObject({ + description: tString + }); + scheme.HttpCredentials = tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + }); + scheme.SetNetworkCookie = tObject({ + name: tString, + value: tString, + url: tOptional(tString), + domain: tOptional(tString), + path: tOptional(tString), + expires: tOptional(tFloat), + httpOnly: tOptional(tBoolean), + secure: tOptional(tBoolean), + sameSite: tOptional(tEnum(["Strict", "Lax", "None"])), + partitionKey: tOptional(tString), + _crHasCrossSiteAncestor: tOptional(tBoolean) + }); + scheme.NetworkCookie = tObject({ + name: tString, + value: tString, + domain: tString, + path: tString, + expires: tFloat, + httpOnly: tBoolean, + secure: tBoolean, + sameSite: tEnum(["Strict", "Lax", "None"]), + partitionKey: tOptional(tString), + _crHasCrossSiteAncestor: tOptional(tBoolean) + }); + scheme.RequestInitializer = tObject({ + frame: tOptional(tChannel(["Frame"])), + serviceWorker: tOptional(tChannel(["Worker"])), + url: tString, + resourceType: tString, + method: tString, + postData: tOptional(tBinary), + headers: tArray(tType("NameValue")), + isNavigationRequest: tBoolean, + redirectedFrom: tOptional(tChannel(["Request"])) + }); + scheme.RequestResponseParams = tOptional(tObject({})); + scheme.RequestResponseResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.RequestRawRequestHeadersParams = tOptional(tObject({})); + scheme.RequestRawRequestHeadersResult = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.RouteInitializer = tObject({ + request: tChannel(["Request"]) + }); + scheme.RouteRedirectNavigationRequestParams = tObject({ + url: tString + }); + scheme.RouteRedirectNavigationRequestResult = tOptional(tObject({})); + scheme.RouteAbortParams = tObject({ + errorCode: tOptional(tString) + }); + scheme.RouteAbortResult = tOptional(tObject({})); + scheme.RouteContinueParams = tObject({ + url: tOptional(tString), + method: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + postData: tOptional(tBinary), + isFallback: tBoolean + }); + scheme.RouteContinueResult = tOptional(tObject({})); + scheme.RouteFulfillParams = tObject({ + status: tOptional(tInt), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tString), + isBase64: tOptional(tBoolean), + fetchResponseUid: tOptional(tString) + }); + scheme.RouteFulfillResult = tOptional(tObject({})); + scheme.WebSocketRouteInitializer = tObject({ + url: tString, + protocols: tArray(tString) + }); + scheme.WebSocketRouteMessageFromPageEvent = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteMessageFromServerEvent = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteClosePageEvent = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteCloseServerEvent = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteConnectParams = tOptional(tObject({})); + scheme.WebSocketRouteConnectResult = tOptional(tObject({})); + scheme.WebSocketRouteEnsureOpenedParams = tOptional(tObject({})); + scheme.WebSocketRouteEnsureOpenedResult = tOptional(tObject({})); + scheme.WebSocketRouteSendToPageParams = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteSendToPageResult = tOptional(tObject({})); + scheme.WebSocketRouteSendToServerParams = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteSendToServerResult = tOptional(tObject({})); + scheme.WebSocketRouteClosePageParams = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteClosePageResult = tOptional(tObject({})); + scheme.WebSocketRouteCloseServerParams = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteCloseServerResult = tOptional(tObject({})); + scheme.ResourceTiming = tObject({ + startTime: tFloat, + domainLookupStart: tFloat, + domainLookupEnd: tFloat, + connectStart: tFloat, + secureConnectionStart: tFloat, + connectEnd: tFloat, + requestStart: tFloat, + responseStart: tFloat + }); + scheme.ResponseInitializer = tObject({ + request: tChannel(["Request"]), + url: tString, + status: tInt, + statusText: tString, + headers: tArray(tType("NameValue")), + timing: tType("ResourceTiming"), + fromServiceWorker: tBoolean + }); + scheme.ResponseBodyParams = tOptional(tObject({})); + scheme.ResponseBodyResult = tObject({ + binary: tBinary + }); + scheme.ResponseSecurityDetailsParams = tOptional(tObject({})); + scheme.ResponseSecurityDetailsResult = tObject({ + value: tOptional(tType("SecurityDetails")) + }); + scheme.ResponseServerAddrParams = tOptional(tObject({})); + scheme.ResponseServerAddrResult = tObject({ + value: tOptional(tType("RemoteAddr")) + }); + scheme.ResponseRawResponseHeadersParams = tOptional(tObject({})); + scheme.ResponseRawResponseHeadersResult = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.ResponseHttpVersionParams = tOptional(tObject({})); + scheme.ResponseHttpVersionResult = tObject({ + value: tString + }); + scheme.ResponseSizesParams = tOptional(tObject({})); + scheme.ResponseSizesResult = tObject({ + sizes: tType("RequestSizes") + }); + scheme.SecurityDetails = tObject({ + issuer: tOptional(tString), + protocol: tOptional(tString), + subjectName: tOptional(tString), + validFrom: tOptional(tFloat), + validTo: tOptional(tFloat) + }); + scheme.RequestSizes = tObject({ + requestBodySize: tInt, + requestHeadersSize: tInt, + responseBodySize: tInt, + responseHeadersSize: tInt + }); + scheme.RemoteAddr = tObject({ + ipAddress: tString, + port: tInt + }); + scheme.WebSocketInitializer = tObject({ + url: tString + }); + scheme.WebSocketOpenEvent = tOptional(tObject({})); + scheme.WebSocketFrameSentEvent = tObject({ + opcode: tInt, + data: tString + }); + scheme.WebSocketFrameReceivedEvent = tObject({ + opcode: tInt, + data: tString + }); + scheme.WebSocketSocketErrorEvent = tObject({ + error: tString + }); + scheme.WebSocketCloseEvent = tOptional(tObject({})); + scheme.PageInitializer = tObject({ + mainFrame: tChannel(["Frame"]), + viewportSize: tOptional(tObject({ + width: tInt, + height: tInt + })), + isClosed: tBoolean, + opener: tOptional(tChannel(["Page"])), + video: tOptional(tChannel(["Artifact"])) + }); + scheme.PageBindingCallEvent = tObject({ + binding: tChannel(["BindingCall"]) + }); + scheme.PageCloseEvent = tOptional(tObject({})); + scheme.PageCrashEvent = tOptional(tObject({})); + scheme.PageDownloadEvent = tObject({ + url: tString, + suggestedFilename: tString, + artifact: tChannel(["Artifact"]) + }); + scheme.PageViewportSizeChangedEvent = tObject({ + viewportSize: tOptional(tObject({ + width: tInt, + height: tInt + })) + }); + scheme.PageFileChooserEvent = tObject({ + element: tChannel(["ElementHandle"]), + isMultiple: tBoolean + }); + scheme.PageFrameAttachedEvent = tObject({ + frame: tChannel(["Frame"]) + }); + scheme.PageFrameDetachedEvent = tObject({ + frame: tChannel(["Frame"]) + }); + scheme.PageLocatorHandlerTriggeredEvent = tObject({ + uid: tInt + }); + scheme.PageRouteEvent = tObject({ + route: tChannel(["Route"]) + }); + scheme.PageScreencastFrameEvent = tObject({ + frameId: tInt, + data: tBinary, + timestamp: tFloat, + viewportWidth: tInt, + viewportHeight: tInt + }); + scheme.PageWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) + }); + scheme.PageWebSocketEvent = tObject({ + webSocket: tChannel(["WebSocket"]) + }); + scheme.PageWorkerEvent = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.PageAddInitScriptParams = tObject({ + source: tString + }); + scheme.PageAddInitScriptResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.PageCloseParams = tObject({ + reason: tOptional(tString) + }); + scheme.PageCloseResult = tOptional(tObject({})); + scheme.PageRunBeforeUnloadParams = tOptional(tObject({})); + scheme.PageRunBeforeUnloadResult = tOptional(tObject({})); + scheme.PageClearConsoleMessagesParams = tOptional(tObject({})); + scheme.PageClearConsoleMessagesResult = tOptional(tObject({})); + scheme.PageConsoleMessagesParams = tObject({ + filter: tOptional(tType("ConsoleMessagesFilter")) + }); + scheme.PageConsoleMessagesResult = tObject({ + messages: tArray(tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + })) + }); + scheme.PageEmulateMediaParams = tObject({ + media: tOptional(tEnum(["screen", "print", "no-override"])), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])) + }); + scheme.PageEmulateMediaResult = tOptional(tObject({})); + scheme.PageExposeBindingParams = tObject({ + name: tString, + noGlobal: tOptional(tBoolean) + }); + scheme.PageExposeBindingResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.PageGoBackParams = tObject({ + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageGoBackResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageGoForwardParams = tObject({ + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageGoForwardResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageRequestGCParams = tOptional(tObject({})); + scheme.PageRequestGCResult = tOptional(tObject({})); + scheme.PageRegisterLocatorHandlerParams = tObject({ + selector: tString, + noWaitAfter: tOptional(tBoolean) + }); + scheme.PageRegisterLocatorHandlerResult = tObject({ + uid: tInt + }); + scheme.PageResolveLocatorHandlerNoReplyParams = tObject({ + uid: tInt, + remove: tOptional(tBoolean) + }); + scheme.PageResolveLocatorHandlerNoReplyResult = tOptional(tObject({})); + scheme.PageUnregisterLocatorHandlerParams = tObject({ + uid: tInt + }); + scheme.PageUnregisterLocatorHandlerResult = tOptional(tObject({})); + scheme.PageReloadParams = tObject({ + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageReloadResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageExpectScreenshotParams = tObject({ + expected: tOptional(tBinary), + isNot: tBoolean, + locator: tOptional(tObject({ + frame: tChannel(["Frame"]), + selector: tString + })), + comparator: tOptional(tString), + maxDiffPixels: tOptional(tInt), + maxDiffPixelRatio: tOptional(tFloat), + threshold: tOptional(tFloat), + fullPage: tOptional(tBoolean), + clip: tOptional(tType("Rect")), + type: tOptional(tEnum(["png", "webp"])), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) + }); + scheme.PageExpectScreenshotResult = tObject({ + actual: tOptional(tBinary) + }); + scheme.PageExpectScreenshotErrorDetails = tObject({ + diff: tOptional(tBinary), + customErrorMessage: tOptional(tString), + actual: tOptional(tBinary), + previous: tOptional(tBinary), + timedOut: tOptional(tBoolean), + log: tOptional(tArray(tString)) + }); + scheme.PageScreenshotParams = tObject({ + type: tOptional(tEnum(["png", "jpeg", "webp"])), + quality: tOptional(tInt), + fullPage: tOptional(tBoolean), + clip: tOptional(tType("Rect")), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) + }); + scheme.PageScreenshotResult = tObject({ + binary: tBinary + }); + scheme.PageSetExtraHTTPHeadersParams = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.PageSetExtraHTTPHeadersResult = tOptional(tObject({})); + scheme.PageSetNetworkInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.PageSetNetworkInterceptionPatternsResult = tOptional(tObject({})); + scheme.PageSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.PageSetWebSocketInterceptionPatternsResult = tOptional(tObject({})); + scheme.PageSetViewportSizeParams = tObject({ + viewportSize: tObject({ + width: tInt, + height: tInt + }) + }); + scheme.PageSetViewportSizeResult = tOptional(tObject({})); + scheme.PageKeyboardDownParams = tObject({ + key: tString + }); + scheme.PageKeyboardDownResult = tOptional(tObject({})); + scheme.PageKeyboardUpParams = tObject({ + key: tString + }); + scheme.PageKeyboardUpResult = tOptional(tObject({})); + scheme.PageKeyboardInsertTextParams = tObject({ + text: tString + }); + scheme.PageKeyboardInsertTextResult = tOptional(tObject({})); + scheme.PageKeyboardTypeParams = tObject({ + text: tString, + delay: tOptional(tFloat) + }); + scheme.PageKeyboardTypeResult = tOptional(tObject({})); + scheme.PageKeyboardPressParams = tObject({ + key: tString, + delay: tOptional(tFloat) + }); + scheme.PageKeyboardPressResult = tOptional(tObject({})); + scheme.PageMouseMoveParams = tObject({ + x: tFloat, + y: tFloat, + steps: tOptional(tInt) + }); + scheme.PageMouseMoveResult = tOptional(tObject({})); + scheme.PageMouseDownParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseDownResult = tOptional(tObject({})); + scheme.PageMouseUpParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseUpResult = tOptional(tObject({})); + scheme.PageMouseClickParams = tObject({ + x: tFloat, + y: tFloat, + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseClickResult = tOptional(tObject({})); + scheme.PageMouseWheelParams = tObject({ + deltaX: tFloat, + deltaY: tFloat + }); + scheme.PageMouseWheelResult = tOptional(tObject({})); + scheme.PageTouchscreenTapParams = tObject({ + x: tFloat, + y: tFloat + }); + scheme.PageTouchscreenTapResult = tOptional(tObject({})); + scheme.PageClearPageErrorsParams = tOptional(tObject({})); + scheme.PageClearPageErrorsResult = tOptional(tObject({})); + scheme.PagePageErrorsParams = tObject({ + filter: tOptional(tType("ConsoleMessagesFilter")) + }); + scheme.PagePageErrorsResult = tObject({ + errors: tArray(tType("SerializedError")) + }); + scheme.PagePdfParams = tObject({ + scale: tOptional(tFloat), + displayHeaderFooter: tOptional(tBoolean), + headerTemplate: tOptional(tString), + footerTemplate: tOptional(tString), + printBackground: tOptional(tBoolean), + landscape: tOptional(tBoolean), + pageRanges: tOptional(tString), + format: tOptional(tString), + width: tOptional(tString), + height: tOptional(tString), + preferCSSPageSize: tOptional(tBoolean), + margin: tOptional(tObject({ + top: tOptional(tString), + bottom: tOptional(tString), + left: tOptional(tString), + right: tOptional(tString) + })), + tagged: tOptional(tBoolean), + outline: tOptional(tBoolean) + }); + scheme.PagePdfResult = tObject({ + pdf: tBinary + }); + scheme.PageRequestsParams = tOptional(tObject({})); + scheme.PageRequestsResult = tObject({ + requests: tArray(tChannel(["Request"])) + }); + scheme.PageStartJSCoverageParams = tObject({ + resetOnNavigation: tOptional(tBoolean), + reportAnonymousScripts: tOptional(tBoolean) + }); + scheme.PageStartJSCoverageResult = tOptional(tObject({})); + scheme.PageStopJSCoverageParams = tOptional(tObject({})); + scheme.PageStopJSCoverageResult = tObject({ + entries: tArray(tObject({ + url: tString, + scriptId: tString, + source: tOptional(tString), + functions: tArray(tObject({ + functionName: tString, + isBlockCoverage: tBoolean, + ranges: tArray(tObject({ + startOffset: tInt, + endOffset: tInt, + count: tInt + })) + })) + })) + }); + scheme.PageStartCSSCoverageParams = tObject({ + resetOnNavigation: tOptional(tBoolean) + }); + scheme.PageStartCSSCoverageResult = tOptional(tObject({})); + scheme.PageStopCSSCoverageParams = tOptional(tObject({})); + scheme.PageStopCSSCoverageResult = tObject({ + entries: tArray(tObject({ + url: tString, + text: tOptional(tString), + ranges: tArray(tObject({ + start: tInt, + end: tInt + })) + })) + }); + scheme.PageBringToFrontParams = tOptional(tObject({})); + scheme.PageBringToFrontResult = tOptional(tObject({})); + scheme.PagePickLocatorParams = tOptional(tObject({})); + scheme.PagePickLocatorResult = tObject({ + selector: tString + }); + scheme.PageCancelPickLocatorParams = tOptional(tObject({})); + scheme.PageCancelPickLocatorResult = tOptional(tObject({})); + scheme.PageHideHighlightParams = tOptional(tObject({})); + scheme.PageHideHighlightResult = tOptional(tObject({})); + scheme.PageScreencastShowOverlayParams = tObject({ + html: tString, + duration: tOptional(tFloat) + }); + scheme.PageScreencastShowOverlayResult = tObject({ + id: tString + }); + scheme.PageScreencastRemoveOverlayParams = tObject({ + id: tString + }); + scheme.PageScreencastRemoveOverlayResult = tOptional(tObject({})); + scheme.PageScreencastChapterParams = tObject({ + title: tString, + description: tOptional(tString), + duration: tOptional(tFloat) + }); + scheme.PageScreencastChapterResult = tOptional(tObject({})); + scheme.PageScreencastSetOverlayVisibleParams = tObject({ + visible: tBoolean + }); + scheme.PageScreencastSetOverlayVisibleResult = tOptional(tObject({})); + scheme.PageScreencastShowActionsParams = tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + }); + scheme.PageScreencastShowActionsResult = tOptional(tObject({})); + scheme.PageScreencastHideActionsParams = tOptional(tObject({})); + scheme.PageScreencastHideActionsResult = tOptional(tObject({})); + scheme.PageScreencastStartParams = tObject({ + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + quality: tOptional(tInt), + fps: tOptional(tInt), + sendFrames: tOptional(tBoolean), + record: tOptional(tBoolean) + }); + scheme.PageScreencastStartResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])) + }); + scheme.PageScreencastFrameAckParams = tObject({ + frameId: tInt + }); + scheme.PageScreencastFrameAckResult = tOptional(tObject({})); + scheme.PageScreencastStopParams = tOptional(tObject({})); + scheme.PageScreencastStopResult = tOptional(tObject({})); + scheme.PageUpdateSubscriptionParams = tObject({ + event: tEnum(["console", "dialog", "dialogClosed", "fileChooser", "request", "response", "requestFinished", "requestFailed"]), + enabled: tBoolean + }); + scheme.PageUpdateSubscriptionResult = tOptional(tObject({})); + scheme.PageSetDockTileParams = tObject({ + image: tBinary + }); + scheme.PageSetDockTileResult = tOptional(tObject({})); + scheme.PageWebStorageItemsParams = tObject({ + kind: tEnum(["local", "session"]) + }); + scheme.PageWebStorageItemsResult = tObject({ + items: tArray(tType("NameValue")) + }); + scheme.PageWebStorageGetItemParams = tObject({ + kind: tEnum(["local", "session"]), + name: tString + }); + scheme.PageWebStorageGetItemResult = tObject({ + value: tOptional(tString) + }); + scheme.PageWebStorageSetItemParams = tObject({ + kind: tEnum(["local", "session"]), + name: tString, + value: tString + }); + scheme.PageWebStorageSetItemResult = tOptional(tObject({})); + scheme.PageWebStorageRemoveItemParams = tObject({ + kind: tEnum(["local", "session"]), + name: tString + }); + scheme.PageWebStorageRemoveItemResult = tOptional(tObject({})); + scheme.PageWebStorageClearParams = tObject({ + kind: tEnum(["local", "session"]) + }); + scheme.PageWebStorageClearResult = tOptional(tObject({})); + scheme.RootInitializer = tOptional(tObject({})); + scheme.RootInitializeParams = tObject({ + sdkLanguage: tType("SDKLanguage") + }); + scheme.RootInitializeResult = tObject({ + playwright: tChannel(["Playwright"]) + }); + scheme.PlaywrightInitializer = tObject({ + chromium: tChannel(["BrowserType"]), + firefox: tChannel(["BrowserType"]), + webkit: tChannel(["BrowserType"]), + android: tChannel(["Android"]), + electron: tChannel(["Electron"]), + utils: tOptional(tChannel(["LocalUtils"])), + preLaunchedBrowser: tOptional(tChannel(["Browser"])), + preConnectedAndroidDevice: tOptional(tChannel(["AndroidDevice"])), + socksSupport: tOptional(tChannel(["SocksSupport"])) + }); + scheme.PlaywrightNewRequestParams = tObject({ + baseURL: tOptional(tString), + userAgent: tOptional(tString), + ignoreHTTPSErrors: tOptional(tBoolean), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + failOnStatusCode: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + maxRedirects: tOptional(tInt), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("NetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))) + })), + tracesDir: tOptional(tString) + }); + scheme.PlaywrightNewRequestResult = tObject({ + request: tChannel(["APIRequestContext"]) + }); + scheme.DebugControllerInitializer = tOptional(tObject({})); + scheme.DebugControllerInspectRequestedEvent = tObject({ + selector: tString, + locator: tString, + ariaSnapshot: tString + }); + scheme.DebugControllerSetModeRequestedEvent = tObject({ + mode: tString + }); + scheme.DebugControllerStateChangedEvent = tObject({ + pageCount: tInt + }); + scheme.DebugControllerSourceChangedEvent = tObject({ + text: tString, + header: tOptional(tString), + footer: tOptional(tString), + actions: tOptional(tArray(tString)) + }); + scheme.DebugControllerPausedEvent = tObject({ + paused: tBoolean + }); + scheme.DebugControllerInitializeParams = tObject({ + codegenId: tString, + sdkLanguage: tType("SDKLanguage") + }); + scheme.DebugControllerInitializeResult = tOptional(tObject({})); + scheme.DebugControllerSetReportStateChangedParams = tObject({ + enabled: tBoolean + }); + scheme.DebugControllerSetReportStateChangedResult = tOptional(tObject({})); + scheme.DebugControllerSetRecorderModeParams = tObject({ + mode: tEnum(["inspecting", "recording", "none"]), + testIdAttributeName: tOptional(tString), + generateAutoExpect: tOptional(tBoolean) + }); + scheme.DebugControllerSetRecorderModeResult = tOptional(tObject({})); + scheme.DebugControllerHighlightParams = tObject({ + selector: tOptional(tString), + ariaTemplate: tOptional(tString) + }); + scheme.DebugControllerHighlightResult = tOptional(tObject({})); + scheme.DebugControllerHideHighlightParams = tOptional(tObject({})); + scheme.DebugControllerHideHighlightResult = tOptional(tObject({})); + scheme.DebugControllerResumeParams = tOptional(tObject({})); + scheme.DebugControllerResumeResult = tOptional(tObject({})); + scheme.DebugControllerKillParams = tOptional(tObject({})); + scheme.DebugControllerKillResult = tOptional(tObject({})); + scheme.SocksSupportInitializer = tOptional(tObject({})); + scheme.SocksSupportSocksRequestedEvent = tObject({ + uid: tString, + host: tString, + port: tInt + }); + scheme.SocksSupportSocksDataEvent = tObject({ + uid: tString, + data: tBinary + }); + scheme.SocksSupportSocksClosedEvent = tObject({ + uid: tString + }); + scheme.SocksSupportSocksConnectedParams = tObject({ + uid: tString, + host: tString, + port: tInt + }); + scheme.SocksSupportSocksConnectedResult = tOptional(tObject({})); + scheme.SocksSupportSocksFailedParams = tObject({ + uid: tString, + errorCode: tString + }); + scheme.SocksSupportSocksFailedResult = tOptional(tObject({})); + scheme.SocksSupportSocksDataParams = tObject({ + uid: tString, + data: tBinary + }); + scheme.SocksSupportSocksDataResult = tOptional(tObject({})); + scheme.SocksSupportSocksErrorParams = tObject({ + uid: tString, + error: tString + }); + scheme.SocksSupportSocksErrorResult = tOptional(tObject({})); + scheme.SocksSupportSocksEndParams = tObject({ + uid: tString + }); + scheme.SocksSupportSocksEndResult = tOptional(tObject({})); + scheme.JsonPipeInitializer = tOptional(tObject({})); + scheme.JsonPipeMessageEvent = tObject({ + message: tAny + }); + scheme.JsonPipeClosedEvent = tObject({ + reason: tOptional(tString) + }); + scheme.JsonPipeSendParams = tObject({ + message: tAny + }); + scheme.JsonPipeSendResult = tOptional(tObject({})); + scheme.JsonPipeCloseParams = tOptional(tObject({})); + scheme.JsonPipeCloseResult = tOptional(tObject({})); + scheme.ExpectedTextValue = tObject({ + string: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + matchSubstring: tOptional(tBoolean), + ignoreCase: tOptional(tBoolean), + normalizeWhiteSpace: tOptional(tBoolean) + }); + scheme.SelectorEngine = tObject({ + name: tString, + source: tString, + contentScript: tOptional(tBoolean) + }); + scheme.FormField = tObject({ + name: tString, + value: tOptional(tString), + file: tOptional(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + })) + }); + scheme.LifecycleEvent = tEnum(["load", "domcontentloaded", "networkidle", "commit"]); + scheme.ConsoleMessagesFilter = tEnum(["all", "since-navigation"]); + scheme.RecorderSource = tObject({ + isRecorded: tBoolean, + id: tString, + label: tString, + text: tString, + language: tString, + highlight: tArray(tObject({ + line: tInt, + type: tString + })), + revealLine: tOptional(tInt), + group: tOptional(tString) + }); + scheme.IndexedDBDatabase = tObject({ + name: tString, + version: tInt, + stores: tArray(tObject({ + name: tString, + autoIncrement: tBoolean, + keyPath: tOptional(tString), + keyPathArray: tOptional(tArray(tString)), + records: tArray(tObject({ + key: tOptional(tAny), + keyEncoded: tOptional(tAny), + value: tOptional(tAny), + valueEncoded: tOptional(tAny) + })), + indexes: tArray(tObject({ + name: tString, + keyPath: tOptional(tString), + keyPathArray: tOptional(tArray(tString)), + multiEntry: tBoolean, + unique: tBoolean + })) + })) + }); + scheme.OPFSEntry = tObject({ + path: tString, + type: tEnum(["file", "directory"]), + base64: tOptional(tString) + }); + scheme.SetOriginStorage = tObject({ + origin: tString, + localStorage: tArray(tType("NameValue")), + indexedDB: tOptional(tArray(tType("IndexedDBDatabase"))), + opfs: tOptional(tArray(tType("OPFSEntry"))) + }); + scheme.OriginStorage = tObject({ + origin: tString, + localStorage: tArray(tType("NameValue")), + indexedDB: tOptional(tArray(tType("IndexedDBDatabase"))), + opfs: tOptional(tArray(tType("OPFSEntry"))) + }); + scheme.RecordHarOptions = tObject({ + content: tOptional(tEnum(["embed", "attach", "omit"])), + mode: tOptional(tEnum(["full", "minimal"])), + urlGlob: tOptional(tString), + urlRegexSource: tOptional(tString), + urlRegexFlags: tOptional(tString), + harPath: tOptional(tString), + resourcesDir: tOptional(tString) + }); + scheme.CDPSessionInitializer = tOptional(tObject({})); + scheme.CDPSessionEventEvent = tObject({ + method: tString, + params: tOptional(tAny) + }); + scheme.CDPSessionCloseEvent = tOptional(tObject({})); + scheme.CDPSessionSendParams = tObject({ + method: tString, + params: tOptional(tAny) + }); + scheme.CDPSessionSendResult = tObject({ + result: tAny + }); + scheme.CDPSessionDetachParams = tOptional(tObject({})); + scheme.CDPSessionDetachResult = tOptional(tObject({})); + scheme.BindingCallInitializer = tObject({ + frame: tChannel(["Frame"]), + name: tString, + args: tArray(tType("SerializedValue")) + }); + scheme.BindingCallRejectParams = tObject({ + error: tType("SerializedError") + }); + scheme.BindingCallRejectResult = tOptional(tObject({})); + scheme.BindingCallResolveParams = tObject({ + result: tType("SerializedArgument") + }); + scheme.BindingCallResolveResult = tOptional(tObject({})); + scheme.DebuggerInitializer = tOptional(tObject({})); + scheme.DebuggerPausedStateChangedEvent = tObject({ + pausedDetails: tOptional(tObject({ + location: tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + }), + title: tString, + stack: tOptional(tString) + })) + }); + scheme.DebuggerApiCallsUpdatedEvent = tObject({ + apiCalls: tArray(tObject({ + id: tString, + title: tString, + location: tOptional(tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + })), + newLogEntries: tArray(tString), + actionPoint: tOptional(tType("Point")), + status: tEnum(["running", "success", "error"]), + error: tOptional(tString) + })) + }); + scheme.DebuggerRequestPauseParams = tOptional(tObject({})); + scheme.DebuggerRequestPauseResult = tOptional(tObject({})); + scheme.DebuggerResumeParams = tOptional(tObject({})); + scheme.DebuggerResumeResult = tOptional(tObject({})); + scheme.DebuggerNextParams = tOptional(tObject({})); + scheme.DebuggerNextResult = tOptional(tObject({})); + scheme.DebuggerRunToParams = tObject({ + location: tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + }) + }); + scheme.DebuggerRunToResult = tOptional(tObject({})); + scheme.DebuggerEnableParams = tOptional(tObject({})); + scheme.DebuggerEnableResult = tOptional(tObject({})); + scheme.DialogInitializer = tObject({ + page: tOptional(tChannel(["Page"])), + type: tString, + message: tString, + defaultValue: tString + }); + scheme.DialogAcceptParams = tObject({ + promptText: tOptional(tString) + }); + scheme.DialogAcceptResult = tOptional(tObject({})); + scheme.DialogDismissParams = tOptional(tObject({})); + scheme.DialogDismissResult = tOptional(tObject({})); + scheme.SerializedValue = tObject({ + n: tOptional(tFloat), + b: tOptional(tBoolean), + s: tOptional(tString), + v: tOptional(tEnum(["null", "undefined", "NaN", "Infinity", "-Infinity", "-0"])), + d: tOptional(tString), + u: tOptional(tString), + bi: tOptional(tString), + ta: tOptional(tObject({ + b: tBinary, + k: tEnum(["i8", "ui8", "ui8c", "i16", "ui16", "i32", "ui32", "f32", "f64", "bi64", "bui64"]) + })), + e: tOptional(tObject({ + m: tString, + n: tString, + s: tString + })), + r: tOptional(tObject({ + p: tString, + f: tString + })), + a: tOptional(tArray(tType("SerializedValue"))), + o: tOptional(tArray(tObject({ + k: tString, + v: tType("SerializedValue") + }))), + h: tOptional(tInt), + fn: tOptional(tString), + id: tOptional(tInt), + ref: tOptional(tInt) + }); + scheme.SerializedArgument = tObject({ + value: tType("SerializedValue"), + handles: tArray(tChannel("*")) + }); + scheme.SerializedError = tObject({ + error: tOptional(tObject({ + message: tString, + name: tString, + stack: tOptional(tString), + code: tOptional(tString) + })), + value: tOptional(tType("SerializedValue")) + }); + scheme.StackFrame = tObject({ + file: tString, + line: tInt, + column: tInt, + function: tOptional(tString) + }); + scheme.VirtualCredential = tObject({ + id: tString, + rpId: tString, + userHandle: tString, + privateKey: tString, + publicKey: tString, + signCount: tInt + }); + scheme.SetVirtualCredential = tObject({ + id: tString, + rpId: tString, + userHandle: tString, + privateKey: tString, + publicKey: tString, + signCount: tOptional(tInt) + }); + scheme.Point = tObject({ + x: tFloat, + y: tFloat + }); + scheme.Rect = tObject({ + x: tFloat, + y: tFloat, + width: tFloat, + height: tFloat + }); + scheme.URLPattern = tObject({ + hash: tString, + hostname: tString, + password: tString, + pathname: tString, + port: tString, + protocol: tString, + search: tString, + username: tString + }); + scheme.NameValue = tObject({ + name: tString, + value: tString + }); + scheme.TracingInitializer = tOptional(tObject({})); + scheme.TracingTracingStartParams = tObject({ + name: tOptional(tString), + snapshotDom: tOptional(tBoolean), + snapshotAria: tOptional(tBoolean), + snapshotScreen: tOptional(tBoolean), + screencast: tOptional(tBoolean), + coverage: tOptional(tBoolean), + live: tOptional(tBoolean) + }); + scheme.TracingTracingStartResult = tOptional(tObject({})); + scheme.TracingTracingStartChunkParams = tObject({ + name: tOptional(tString), + title: tOptional(tString) + }); + scheme.TracingTracingStartChunkResult = tObject({ + traceName: tString + }); + scheme.TracingTracingGroupParams = tObject({ + name: tString, + location: tOptional(tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + })) + }); + scheme.TracingTracingGroupResult = tOptional(tObject({})); + scheme.TracingTracingGroupEndParams = tOptional(tObject({})); + scheme.TracingTracingGroupEndResult = tOptional(tObject({})); + scheme.TracingTracingStopChunkParams = tObject({ + mode: tEnum(["archive", "discard", "entries"]) + }); + scheme.TracingTracingStopChunkResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])), + entries: tOptional(tArray(tType("NameValue"))) + }); + scheme.TracingTracingStopParams = tOptional(tObject({})); + scheme.TracingTracingStopResult = tOptional(tObject({})); + scheme.TracingHarStartParams = tObject({ + page: tOptional(tChannel(["Page"])), + options: tType("RecordHarOptions") + }); + scheme.TracingHarStartResult = tObject({ + harId: tString + }); + scheme.TracingHarExportParams = tObject({ + harId: tOptional(tString), + mode: tEnum(["archive", "entries"]) + }); + scheme.TracingHarExportResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])), + entries: tOptional(tArray(tType("NameValue"))) + }); + scheme.WorkerInitializer = tObject({ + url: tString + }); + scheme.WorkerConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + }); + scheme.WorkerCloseEvent = tOptional(tObject({})); + scheme.WorkerDisconnectParams = tObject({ + reason: tOptional(tString) + }); + scheme.WorkerDisconnectResult = tOptional(tObject({})); + scheme.WorkerEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.WorkerEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.WorkerEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.WorkerEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.WorkerUpdateSubscriptionParams = tObject({ + event: tEnum(["console"]), + enabled: tBoolean + }); + scheme.WorkerUpdateSubscriptionResult = tOptional(tObject({})); + } +}); + +// packages/playwright-core/src/server/callLog.ts +function compressCallLog(log2) { + const lines = []; + for (const block of findRepeatedSubsequences(log2)) { + for (let i = 0; i < block.sequence.length; i++) { + const line = block.sequence[i]; + const leadingWhitespace = line.match(/^\s*/); + const whitespacePrefix = " " + leadingWhitespace?.[0] || ""; + const countPrefix = `${block.count} \xD7 `; + if (block.count > 1 && i === 0) + lines.push(whitespacePrefix + countPrefix + line.trim()); + else if (block.count > 1) + lines.push(whitespacePrefix + " ".repeat(countPrefix.length - 2) + "- " + line.trim()); + else + lines.push(whitespacePrefix + "- " + line.trim()); + } + } + return lines; +} +function findRepeatedSubsequences(s) { + const n = s.length; + const result2 = []; + let i = 0; + const arraysEqual = (a1, a2) => { + if (a1.length !== a2.length) + return false; + for (let j = 0; j < a1.length; j++) { + if (a1[j] !== a2[j]) + return false; + } + return true; + }; + while (i < n) { + let maxRepeatCount = 1; + let maxRepeatSubstr = [s[i]]; + let maxRepeatLength = 1; + for (let p = 1; p <= n - i; p++) { + const substr = s.slice(i, i + p); + let k = 1; + while (i + p * k <= n && arraysEqual(s.slice(i + p * (k - 1), i + p * k), substr)) + k += 1; + k -= 1; + if (k > 1 && k * p > maxRepeatCount * maxRepeatLength) { + maxRepeatCount = k; + maxRepeatSubstr = substr; + maxRepeatLength = p; + } + } + result2.push({ sequence: maxRepeatSubstr, count: maxRepeatCount }); + i += maxRepeatLength * maxRepeatCount; + } + return result2; +} +var findRepeatedSubsequencesForTest; +var init_callLog = __esm({ + "packages/playwright-core/src/server/callLog.ts"() { + "use strict"; + findRepeatedSubsequencesForTest = findRepeatedSubsequences; + } +}); + +// packages/playwright-core/src/server/dispatchers/dispatcher.ts +function setMaxDispatchersForTest(value2) { + maxDispatchersOverride = value2; +} +function maxDispatchersForBucket(gcBucket) { + return maxDispatchersOverride ?? { + "JSHandle": 1e5, + "ElementHandle": 1e5 + }[gcBucket] ?? 1e4; +} +var import_events5, metadataValidator, waitInfoValidator, maxDispatchersOverride, Dispatcher, RootDispatcher, DispatcherConnection; +var init_dispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/dispatcher.ts"() { + "use strict"; + import_events5 = require("events"); + init_protocolMetainfo(); + init_eventsHelper(); + init_debug(); + init_assert(); + init_time(); + init_validator(); + init_errors(); + init_instrumentation(); + init_callLog(); + init_progress(); + metadataValidator = createMetadataValidator(); + waitInfoValidator = createWaitInfoValidator(); + Dispatcher = class extends import_events5.EventEmitter { + constructor(parent, object, type3, initializer, gcBucket) { + super(); + this._dispatchers = /* @__PURE__ */ new Map(); + this._disposed = false; + this._eventListeners = []; + this.connection = parent instanceof DispatcherConnection ? parent : parent.connection; + this._parent = parent instanceof DispatcherConnection ? void 0 : parent; + const guid = object.guid; + this._guid = guid; + this._type = type3; + this._object = object; + this._gcBucket = gcBucket ?? type3; + this.connection.registerDispatcher(this); + if (this._parent) { + assert(!this._parent._dispatchers.has(guid)); + this._parent._dispatchers.set(guid, this); + } + if (this._parent) + this.connection.sendCreate(this._parent, type3, guid, initializer); + this.connection.maybeDisposeStaleDispatchers(this._gcBucket); + } + parentScope() { + return this._parent; + } + addObjectListener(eventName, handler) { + this._eventListeners.push(eventsHelper.addEventListener(this._object, eventName, handler)); + } + adopt(child) { + if (child._parent === this) + return; + const oldParent = child._parent; + oldParent._dispatchers.delete(child._guid); + this._dispatchers.set(child._guid, child); + child._parent = this; + this.connection.sendAdopt(this, child); + } + createProgressController(callMetadata, pendingAbortError) { + return ProgressController.createForSdkObject(this._object, callMetadata, pendingAbortError); + } + _dispatchEvent(method2, params2) { + if (this._disposed) { + if (isUnderTest()) + throw new Error(`${this._guid} is sending "${String(method2)}" event after being disposed`); + return; + } + this.connection.sendEvent(this, method2, params2); + } + _dispose(reason) { + this._disposeRecursively(new TargetClosedError(this._object.closeReason())); + this.connection.sendDispose(this, reason); + } + _onDispose() { + } + async stopPendingOperations(error) { + const guids = /* @__PURE__ */ new Set(); + const collect = (dispatcher) => { + guids.add(dispatcher._guid); + for (const child of [...dispatcher._dispatchers.values()]) + collect(child); + }; + collect(this); + await this.connection.abortControllersForGuids(guids, error); + } + _disposeRecursively(error) { + assert(!this._disposed, `${this._guid} is disposed more than once`); + this._onDispose(); + this._disposed = true; + eventsHelper.removeEventListeners(this._eventListeners); + this._parent?._dispatchers.delete(this._guid); + const list = this.connection._dispatchersByBucket.get(this._gcBucket); + list?.delete(this._guid); + this.connection._dispatcherByGuid.delete(this._guid); + this.connection._dispatcherByObject.delete(this._object); + for (const dispatcher of [...this._dispatchers.values()]) + dispatcher._disposeRecursively(error); + this._dispatchers.clear(); + } + _debugScopeState() { + return { + _guid: this._guid, + objects: Array.from(this._dispatchers.values()).map((o) => o._debugScopeState()) + }; + } + }; + RootDispatcher = class extends Dispatcher { + constructor(connection, createPlaywright2) { + super(connection, createRootSdkObject(), "Root", {}); + this.createPlaywright = createPlaywright2; + this._initialized = false; + } + async initialize(params2, progress2) { + assert(this.createPlaywright); + assert(!this._initialized); + this._initialized = true; + return { + playwright: await progress2.race(this.createPlaywright(this, params2)) + }; + } + }; + DispatcherConnection = class { + constructor(isInProcess) { + this._dispatcherByGuid = /* @__PURE__ */ new Map(); + this._dispatcherByObject = /* @__PURE__ */ new Map(); + this._dispatchersByBucket = /* @__PURE__ */ new Map(); + this.onmessage = (message) => { + }; + this._waitOperations = /* @__PURE__ */ new Map(); + this._activeProgressControllers = /* @__PURE__ */ new Map(); + this._isInProcess = !!isInProcess; + } + async abortControllersForGuids(guids, error) { + const controllers = []; + for (const entry of this._activeProgressControllers.values()) { + if (entry.controller?.metadata.objectId && guids.has(entry.controller.metadata.objectId)) { + entry.abortError = error; + controllers.push(entry.controller); + } + } + await Promise.all(controllers.map((controller) => controller.abort(error))); + } + sendEvent(dispatcher, event, params2) { + const validator = findValidator(dispatcher._type, event, "Event"); + params2 = validator(params2, "", this._validatorToWireContext()); + this.onmessage({ guid: dispatcher._guid, method: event, params: params2 }); + } + sendCreate(parent, type3, guid, initializer) { + const validator = findValidator(type3, "", "Initializer"); + initializer = validator(initializer, "", this._validatorToWireContext()); + this.onmessage({ guid: parent._guid, method: "__create__", params: { type: type3, initializer, guid } }); + } + sendAdopt(parent, dispatcher) { + this.onmessage({ guid: parent._guid, method: "__adopt__", params: { guid: dispatcher._guid } }); + } + sendDispose(dispatcher, reason) { + this.onmessage({ guid: dispatcher._guid, method: "__dispose__", params: { reason } }); + } + _validatorToWireContext() { + return { + tChannelImpl: this._tChannelImplToWire.bind(this), + binary: this._isInProcess ? "buffer" : "toBase64", + isUnderTest + }; + } + _validatorFromWireContext() { + return { + tChannelImpl: this._tChannelImplFromWire.bind(this), + binary: this._isInProcess ? "buffer" : "fromBase64", + isUnderTest + }; + } + _tChannelImplFromWire(names, arg2, path66, context) { + if (arg2 && typeof arg2 === "object" && typeof arg2.guid === "string") { + const guid = arg2.guid; + const dispatcher = this._dispatcherByGuid.get(guid); + if (!dispatcher) + throw new ValidationError(`${path66}: no object with guid ${guid}`); + if (names !== "*" && !names.includes(dispatcher._type)) + throw new ValidationError(`${path66}: object with guid ${guid} has type ${dispatcher._type}, expected ${names.toString()}`); + return dispatcher; + } + throw new ValidationError(`${path66}: expected guid for ${names.toString()}`); + } + _tChannelImplToWire(names, arg2, path66, context) { + if (arg2 instanceof Dispatcher) { + if (names !== "*" && !names.includes(arg2._type)) + throw new ValidationError(`${path66}: dispatcher with guid ${arg2._guid} has type ${arg2._type}, expected ${names.toString()}`); + return { guid: arg2._guid }; + } + throw new ValidationError(`${path66}: expected dispatcher ${names.toString()}`); + } + existingDispatcher(object) { + return this._dispatcherByObject.get(object); + } + registerDispatcher(dispatcher) { + assert(!this._dispatcherByGuid.has(dispatcher._guid)); + this._dispatcherByGuid.set(dispatcher._guid, dispatcher); + this._dispatcherByObject.set(dispatcher._object, dispatcher); + let list = this._dispatchersByBucket.get(dispatcher._gcBucket); + if (!list) { + list = /* @__PURE__ */ new Set(); + this._dispatchersByBucket.set(dispatcher._gcBucket, list); + } + list.add(dispatcher._guid); + } + maybeDisposeStaleDispatchers(gcBucket) { + const maxDispatchers = maxDispatchersForBucket(gcBucket); + const list = this._dispatchersByBucket.get(gcBucket); + if (!list || list.size <= maxDispatchers) + return; + const dispatchersArray = [...list]; + const disposeCount = maxDispatchers / 10 | 0; + this._dispatchersByBucket.set(gcBucket, new Set(dispatchersArray.slice(disposeCount))); + for (let i = 0; i < disposeCount; ++i) { + const d = this._dispatcherByGuid.get(dispatchersArray[i]); + if (!d) + continue; + d._dispose("gc"); + } + } + async dispatch(message) { + const { id, guid, method: method2, params: params2, metadata } = message; + const dispatcher = this._dispatcherByGuid.get(guid); + if (method2 === "__waitInfo__") { + if (dispatcher) + await this._dispatchWaitInfo(id, dispatcher, params2, metadata); + return; + } + if (method2 === "__abort__") { + const entry = this._activeProgressControllers.get(params2.id); + if (!entry) + return; + entry.abortError = new AbortError(params2.reason); + const controller = entry.controller; + await controller?.abort(entry.abortError); + return; + } + if (!dispatcher) { + this.onmessage({ id, error: serializeError(new TargetClosedError(void 0)) }); + return; + } + let validParams; + let validMetadata; + try { + const validator = findValidator(dispatcher._type, method2, "Params"); + const validatorContext = this._validatorFromWireContext(); + validParams = validator(params2, "", validatorContext); + validMetadata = metadataValidator(metadata, "", validatorContext); + if (typeof dispatcher[method2] !== "function") + throw new Error(`Mismatching dispatcher: "${dispatcher._type}" does not implement "${method2}"`); + } catch (e) { + this.onmessage({ id, error: serializeError(e) }); + return; + } + const metainfo = getMetainfo({ type: dispatcher._type, method: method2 }); + if (metainfo?.internal) { + validMetadata.internal = true; + } + const sdkObject = dispatcher._object; + const callMetadata = { + id, + location: validMetadata.location, + title: validMetadata.title, + internal: validMetadata.internal, + objectId: sdkObject.guid, + startTime: monotonicTime(), + endTime: 0, + type: dispatcher._type, + method: method2, + params: params2 || {}, + timeout: validMetadata.timeout, + log: [] + }; + const abortControllerEntry = {}; + this._activeProgressControllers.set(id, abortControllerEntry); + const swapProgressController = () => { + const controller = dispatcher.createProgressController(callMetadata, abortControllerEntry.abortError); + abortControllerEntry.controller = controller; + return controller; + }; + const beforeController = swapProgressController(); + await beforeController.run((progress2) => sdkObject.instrumentation.onBeforeCall(progress2, sdkObject), 3e3).catch(() => { + }); + const response2 = { id }; + try { + if (this._dispatcherByGuid.get(guid) !== dispatcher) + throw new TargetClosedError(sdkObject.closeReason()); + const controller = swapProgressController(); + const result2 = await controller.run((progress2) => dispatcher[method2](validParams, progress2), validMetadata.timeout); + const validator = findValidator(dispatcher._type, method2, "Result"); + response2.result = validator(result2, "", this._validatorToWireContext()); + callMetadata.result = result2; + } catch (e) { + e = rewriteErrorForClosedTarget(e, sdkObject.closeReason()); + response2.error = serializeError(e); + const detailsValidator = maybeFindValidator(dispatcher._type, method2, "ErrorDetails"); + if (detailsValidator) + response2.errorDetails = detailsValidator(e?.details ?? {}, "", this._validatorToWireContext()); + callMetadata.error = response2.error; + } finally { + callMetadata.endTime = monotonicTime(); + const afterController = swapProgressController(); + await afterController.run((progress2) => sdkObject.instrumentation.onAfterCall(progress2, sdkObject), 3e3).catch(() => { + }); + if (metainfo?.slowMo) + await this._doSlowMo(sdkObject); + this._activeProgressControllers.delete(id); + } + if (response2.error) + response2.log = compressCallLog(callMetadata.log); + this.onmessage(response2); + } + async _doSlowMo(sdkObject) { + const slowMo = sdkObject.attribution.browser?.options.slowMo; + if (slowMo) + await new Promise((f) => setTimeout(f, slowMo)); + } + async _dispatchWaitInfo(id, dispatcher, params2, metadata) { + let info; + let validMetadata; + try { + const validatorContext = this._validatorFromWireContext(); + info = waitInfoValidator(params2, "", validatorContext); + validMetadata = metadataValidator(metadata, "", validatorContext); + } catch { + return; + } + const sdkObject = dispatcher._object; + if (info.phase === "before") { + const callMetadata = { + id, + location: validMetadata.location, + title: validMetadata.title, + internal: validMetadata.internal, + objectId: sdkObject.guid, + startTime: monotonicTime(), + endTime: 0, + type: dispatcher._type, + method: "__waitInfo__", + params: params2 || {}, + log: [] + }; + this._waitOperations.set(info.waitId, callMetadata); + const controller = ProgressController.createForSdkObject(sdkObject, callMetadata); + await controller.run((progress2) => sdkObject.instrumentation.onBeforeCall(progress2, sdkObject).catch(() => { + })); + return; + } + const originalMetadata = this._waitOperations.get(info.waitId); + if (!originalMetadata) + return; + if (info.phase === "log" && info.message) { + originalMetadata.log.push(info.message); + sdkObject.instrumentation.onCallLog(sdkObject, originalMetadata, "api", info.message); + return; + } + if (info.phase === "after") { + originalMetadata.endTime = monotonicTime(); + originalMetadata.error = info.error ? { error: { name: "Error", message: info.error } } : void 0; + this._waitOperations.delete(info.waitId); + const controller = ProgressController.createForSdkObject(sdkObject, originalMetadata); + await controller.run((progress2) => sdkObject.instrumentation.onAfterCall(progress2, sdkObject).catch(() => { + })); + } + } + }; + } +}); + +// packages/isomorphic/utilityScriptSerializers.ts +function isRegExp5(obj) { + try { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; + } catch (error) { + return false; + } +} +function isDate2(obj) { + try { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; + } catch (error) { + return false; + } +} +function isURL2(obj) { + try { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; + } catch (error) { + return false; + } +} +function isError3(obj) { + try { + return obj instanceof Error || obj && Object.getPrototypeOf(obj)?.name === "Error"; + } catch (error) { + return false; + } +} +function isTypedArray(obj, constructor) { + try { + return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`; + } catch (error) { + return false; + } +} +function isArrayBuffer(obj) { + try { + return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]"; + } catch (error) { + return false; + } +} +function isMap(obj) { + try { + return obj instanceof Map || Object.prototype.toString.call(obj) === "[object Map]"; + } catch (error) { + return false; + } +} +function isSet(obj) { + try { + return obj instanceof Set || Object.prototype.toString.call(obj) === "[object Set]"; + } catch (error) { + return false; + } +} +function typedArrayToBase64(array) { + if ("toBase64" in array) + return array.toBase64(); + const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join(""); + return btoa(binary); +} +function base64ToTypedArray(base64, TypedArrayConstructor) { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) + bytes[i] = binary.charCodeAt(i); + return new TypedArrayConstructor(bytes.buffer); +} +function parseEvaluationResultValue(value2, handles = [], refs = /* @__PURE__ */ new Map()) { + if (Object.is(value2, void 0)) + return void 0; + if (typeof value2 === "object" && value2) { + if ("ref" in value2) + return refs.get(value2.ref); + if ("v" in value2) { + if (value2.v === "undefined") + return void 0; + if (value2.v === "null") + return null; + if (value2.v === "NaN") + return NaN; + if (value2.v === "Infinity") + return Infinity; + if (value2.v === "-Infinity") + return -Infinity; + if (value2.v === "-0") + return -0; + return void 0; + } + if ("d" in value2) { + return new Date(value2.d); + } + if ("u" in value2) + return new URL(value2.u); + if ("bi" in value2) + return BigInt(value2.bi); + if ("e" in value2) { + const error = new Error(value2.e.m); + error.name = value2.e.n; + error.stack = value2.e.s; + return error; + } + if ("r" in value2) + return new RegExp(value2.r.p, value2.r.f); + if ("a" in value2) { + const result2 = []; + refs.set(value2.id, result2); + for (const a of value2.a) + result2.push(parseEvaluationResultValue(a, handles, refs)); + return result2; + } + if ("o" in value2) { + const result2 = {}; + refs.set(value2.id, result2); + for (const { k, v } of value2.o) { + if (k === "__proto__") + continue; + result2[k] = parseEvaluationResultValue(v, handles, refs); + } + return result2; + } + if ("m" in value2) { + const result2 = /* @__PURE__ */ new Map(); + refs.set(value2.id, result2); + for (const { k, v } of value2.m) + result2.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs)); + return result2; + } + if ("s" in value2) { + const result2 = /* @__PURE__ */ new Set(); + refs.set(value2.id, result2); + for (const item of value2.s) + result2.add(parseEvaluationResultValue(item, handles, refs)); + return result2; + } + if ("h" in value2) + return handles[value2.h]; + if ("fn" in value2) { + const name = value2.fn; + return (...args) => globalThis[kBindingsControllerProperty].callBinding(name, ...args); + } + if ("ta" in value2) + return base64ToTypedArray(value2.ta.b, typedArrayConstructors[value2.ta.k]); + if ("ab" in value2) + return base64ToTypedArray(value2.ab.b, Uint8Array).buffer; + } + return value2; +} +function serializeAsCallArgument(value2, handleSerializer, options = {}) { + return serialize(value2, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0, extendedSerialization: options.extendedSerialization }); +} +function serialize(value2, handleSerializer, visitorInfo) { + if (value2 && typeof value2 === "object") { + if (typeof globalThis.Window === "function" && value2 instanceof globalThis.Window) + return "ref: "; + if (typeof globalThis.Document === "function" && value2 instanceof globalThis.Document) + return "ref: "; + if (typeof globalThis.Node === "function" && value2 instanceof globalThis.Node) + return "ref: "; + } + return innerSerialize(value2, handleSerializer, visitorInfo); +} +function innerSerialize(value2, handleSerializer, visitorInfo) { + const result2 = handleSerializer(value2); + if ("fallThrough" in result2) + value2 = result2.fallThrough; + else + return result2; + if (typeof value2 === "symbol") + return { v: "undefined" }; + if (Object.is(value2, void 0)) + return { v: "undefined" }; + if (Object.is(value2, null)) + return { v: "null" }; + if (Object.is(value2, NaN)) + return { v: "NaN" }; + if (Object.is(value2, Infinity)) + return { v: "Infinity" }; + if (Object.is(value2, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value2, -0)) + return { v: "-0" }; + if (typeof value2 === "boolean") + return value2; + if (typeof value2 === "number") + return value2; + if (typeof value2 === "string") + return value2; + if (typeof value2 === "bigint") + return { bi: value2.toString() }; + if (isError3(value2)) { + let stack; + if (value2.stack?.startsWith(value2.name + ": " + value2.message)) { + stack = value2.stack; + } else { + stack = `${value2.name}: ${value2.message} +${value2.stack}`; + } + return { e: { n: value2.name, m: value2.message, s: stack } }; + } + if (isDate2(value2)) + return { d: value2.toJSON() }; + if (isURL2(value2)) + return { u: value2.toJSON() }; + if (isRegExp5(value2)) + return { r: { p: value2.source, f: value2.flags } }; + for (const [k, ctor] of Object.entries(typedArrayConstructors)) { + if (isTypedArray(value2, ctor)) + return { ta: { b: typedArrayToBase64(value2), k } }; + } + if (isArrayBuffer(value2)) + return { ab: { b: typedArrayToBase64(new Uint8Array(value2)) } }; + const id = visitorInfo.visited.get(value2); + if (id) + return { ref: id }; + if (visitorInfo.extendedSerialization) { + if (isMap(value2)) { + const m = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + const iterator = value2.entries(); + const next = (/* @__PURE__ */ new Map()).entries().next; + while (true) { + const entry = next.call(iterator); + if (entry.done) + break; + m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) }); + } + return { m, id: id2 }; + } + if (isSet(value2)) { + const s = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + const iterator = value2.values(); + const next = (/* @__PURE__ */ new Set()).values().next; + while (true) { + const entry = next.call(iterator); + if (entry.done) + break; + s.push(serialize(entry.value, handleSerializer, visitorInfo)); + } + return { s, id: id2 }; + } + } + if (Array.isArray(value2)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (let i = 0; i < value2.length; ++i) + a.push(serialize(value2[i], handleSerializer, visitorInfo)); + return { a, id: id2 }; + } + if (typeof value2 === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (const name of Object.keys(value2)) { + let item; + try { + item = value2[name]; + } catch (e) { + continue; + } + if (name === "toJSON" && typeof item === "function") + o.push({ k: name, v: { o: [], id: 0 } }); + else + o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) }); + } + let jsonWrapper; + try { + if (o.length === 0 && value2.toJSON && typeof value2.toJSON === "function") + jsonWrapper = { value: value2.toJSON() }; + } catch (e) { + } + if (jsonWrapper) + return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo); + return { o, id: id2 }; + } + if (typeof value2 === "function" && value2.name.startsWith(kFunctionBindingPrefix)) + return { fn: value2.name }; +} +var kFunctionBindingPrefix, kBindingsControllerProperty, typedArrayConstructors; +var init_utilityScriptSerializers = __esm({ + "packages/isomorphic/utilityScriptSerializers.ts"() { + "use strict"; + kFunctionBindingPrefix = "__pw_fn_"; + kBindingsControllerProperty = "__playwright__binding__controller__"; + typedArrayConstructors = { + i8: Int8Array, + ui8: Uint8Array, + ui8c: Uint8ClampedArray, + i16: Int16Array, + ui16: Uint16Array, + i32: Int32Array, + ui32: Uint32Array, + // TODO: add Float16Array once it's in baseline + f32: Float32Array, + f64: Float64Array, + bi64: BigInt64Array, + bui64: BigUint64Array + }; + } +}); + +// packages/playwright-core/src/generated/utilityScriptSource.ts +var source4; +var init_utilityScriptSource = __esm({ + "packages/playwright-core/src/generated/utilityScriptSource.ts"() { + "use strict"; + source4 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/utilityScript.ts\nvar utilityScript_exports = {};\n__export(utilityScript_exports, {\n UtilityScript: () => UtilityScript\n});\nmodule.exports = __toCommonJS(utilityScript_exports);\n\n// packages/isomorphic/utilityScriptSerializers.ts\nvar kFunctionBindingPrefix = "__pw_fn_";\nvar kBindingsControllerProperty = "__playwright__binding__controller__";\nfunction isRegExp(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\n } catch (error) {\n return false;\n }\n}\nfunction isMap(obj) {\n try {\n return obj instanceof Map || Object.prototype.toString.call(obj) === "[object Map]";\n } catch (error) {\n return false;\n }\n}\nfunction isSet(obj) {\n try {\n return obj instanceof Set || Object.prototype.toString.call(obj) === "[object Set]";\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("m" in value) {\n const result = /* @__PURE__ */ new Map();\n refs.set(value.id, result);\n for (const { k, v } of value.m)\n result.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs));\n return result;\n }\n if ("s" in value) {\n const result = /* @__PURE__ */ new Set();\n refs.set(value.id, result);\n for (const item of value.s)\n result.add(parseEvaluationResultValue(item, handles, refs));\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("fn" in value) {\n const name = value.fn;\n return (...args) => globalThis[kBindingsControllerProperty].callBinding(name, ...args);\n }\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer, options = {}) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0, extendedSerialization: options.extendedSerialization });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (visitorInfo.extendedSerialization) {\n if (isMap(value)) {\n const m = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.entries();\n const next = (/* @__PURE__ */ new Map()).entries().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) });\n }\n return { m, id: id2 };\n }\n if (isSet(value)) {\n const s = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.values();\n const next = (/* @__PURE__ */ new Set()).values().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n s.push(serialize(entry.value, handleSerializer, visitorInfo));\n }\n return { s, id: id2 };\n }\n }\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n if (typeof value === "function" && value.name.startsWith(kFunctionBindingPrefix))\n return { fn: value.name };\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date,\n AbortSignal: global.AbortSignal,\n Temporal: global.Temporal\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n return returnByValue ? this._promiseAwareJsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _promiseAwareJsonValueNoThrow(value) {\n const safeJson = (value2) => {\n try {\n return this.jsonValue(true, value2);\n } catch (e) {\n return void 0;\n }\n };\n if (value && typeof value === "object" && typeof value.then === "function") {\n return (async () => {\n const promiseValue = await value;\n return safeJson(promiseValue);\n })();\n }\n return safeJson(value);\n }\n};\n'; + } +}); + +// packages/playwright-core/src/server/javascript.ts +async function evaluate(context, returnByValue, pageFunction, ...args) { + return evaluateExpression(context, String(pageFunction), { returnByValue, isFunction: typeof pageFunction === "function" }, ...args); +} +async function evaluateExpression(context, expression2, options, ...args) { + expression2 = normalizeEvaluationExpression(expression2, options.isFunction); + const handles = []; + const toDispose = []; + const pushHandle = (handle) => { + handles.push(handle); + return handles.length - 1; + }; + args = args.map((arg2) => serializeAsCallArgument(arg2, (handle) => { + if (handle instanceof JSHandle) { + if (!handle._objectId) + return { fallThrough: handle._value }; + if (handle._disposed) + throw new JavaScriptErrorInEvaluate("JSHandle is disposed!"); + const adopted = context.adoptIfNeeded(handle); + if (adopted === null) + return { h: pushHandle(Promise.resolve(handle)) }; + toDispose.push(adopted); + return { h: pushHandle(adopted) }; + } + return { fallThrough: handle }; + })); + const utilityScriptObjects = []; + for (const handle of await Promise.all(handles)) { + if (handle._context !== context) + throw new JavaScriptErrorInEvaluate("JSHandles can be evaluated only in the context they were created!"); + utilityScriptObjects.push(handle); + } + const utilityScriptValues = [options.isFunction, options.returnByValue, expression2, args.length, ...args]; + const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`; + try { + return await context._evaluateWithArguments(script, options.returnByValue || false, utilityScriptValues, utilityScriptObjects); + } finally { + toDispose.map((handlePromise) => handlePromise.then((handle) => handle.dispose())); + } +} +function parseUnserializableValue(unserializableValue) { + if (unserializableValue === "NaN") + return NaN; + if (unserializableValue === "Infinity") + return Infinity; + if (unserializableValue === "-Infinity") + return -Infinity; + if (unserializableValue === "-0") + return -0; +} +function normalizeEvaluationExpression(expression2, isFunction2) { + expression2 = expression2.trim(); + if (isFunction2) { + try { + new Function("(" + expression2 + ")"); + } catch (e1) { + if (expression2.startsWith("async ")) + expression2 = "async function " + expression2.substring("async ".length); + else + expression2 = "function " + expression2; + try { + new Function("(" + expression2 + ")"); + } catch (e2) { + throw new Error("Passed function is not well-serializable!"); + } + } + } + if (/^(async)?\s*function(\s|\()/.test(expression2)) + expression2 = "(" + expression2 + ")"; + return expression2; +} +function isJavaScriptErrorInEvaluate(error) { + return error instanceof JavaScriptErrorInEvaluate; +} +function sparseArrayToString(entries) { + const arrayEntries = []; + for (const { name, value: value2 } of entries) { + const index = +name; + if (isNaN(index) || index < 0) + continue; + arrayEntries.push({ index, value: value2 }); + } + arrayEntries.sort((a, b) => a.index - b.index); + let lastIndex = -1; + const tokens = []; + for (const { index, value: value2 } of arrayEntries) { + const emptyItems = index - lastIndex - 1; + if (emptyItems === 1) + tokens.push(`empty`); + else if (emptyItems > 1) + tokens.push(`empty x ${emptyItems}`); + tokens.push(String(value2)); + lastIndex = index; + } + return "[" + tokens.join(", ") + "]"; +} +var ExecutionContext, JSHandle, JavaScriptErrorInEvaluate, snapshottedFunctionBuiltins, snapshottedObjectBuiltins, snapshottedTimerBuiltins, saveGlobalsSnapshotSource, mainWorldGlobalsSnapshotSource; +var init_javascript = __esm({ + "packages/playwright-core/src/server/javascript.ts"() { + "use strict"; + init_utilityScriptSerializers(); + init_manualPromise(); + init_debug(); + init_instrumentation(); + init_utilityScriptSource(); + ExecutionContext = class extends SdkObject { + constructor(parent, delegate, worldNameForTest, options) { + super(parent, "execution-context"); + this._contextDestroyedScope = new LongStandingScope(); + this.worldNameForTest = worldNameForTest; + this._noUtilityWorld = options?.noUtilityWorld; + this.delegate = delegate; + } + contextDestroyed(reason) { + this._contextDestroyedScope.close(new Error(reason)); + } + async raceAgainstContextDestroyed(promise) { + return this._contextDestroyedScope.race(promise); + } + rawEvaluateJSON(expression2) { + return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateJSON(expression2)); + } + rawEvaluateHandle(expression2) { + return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, expression2)); + } + async _evaluateWithArguments(expression2, returnByValue, values, handles) { + const utilityScript = await this._utilityScript(); + return this.raceAgainstContextDestroyed(this.delegate.evaluateWithArguments(expression2, returnByValue, utilityScript, values, handles)); + } + getProperties(object) { + return this.raceAgainstContextDestroyed(this.delegate.getProperties(object)); + } + _releaseHandle(handle) { + return this.delegate.releaseHandle(handle); + } + adoptIfNeeded(handle) { + return null; + } + _utilityScript() { + if (!this._utilityScriptPromise) { + const globalsSnapshot = this._noUtilityWorld ? mainWorldGlobalsSnapshotSource : ""; + const source14 = ` + (() => { + ${globalsSnapshot} + const module = {}; + ${source4} + return new (module.exports.UtilityScript())(globalThis, ${isUnderTest()}); + })();`; + this._utilityScriptPromise = this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, source14)).then((handle) => { + handle._setPreview("UtilityScript"); + return handle; + }); + } + return this._utilityScriptPromise; + } + }; + JSHandle = class extends SdkObject { + constructor(context, type3, preview, objectId, value2) { + super(context, "handle"); + this.__jshandle = true; + this._disposed = false; + this._context = context; + this._objectId = objectId; + this._value = value2; + this._objectType = type3; + this._preview = this._objectId ? preview || `JSHandle@${this._objectType}` : String(value2); + if (this._objectId && globalThis.leakedJSHandles) + globalThis.leakedJSHandles.set(this, new Error("Leaked JSHandle")); + } + async evaluateExpression(progress2, expression2, options, arg2) { + return await progress2.race(this.internalEvaluateExpression(expression2, options, arg2)); + } + async evaluateExpressionHandle(progress2, expression2, options, arg2) { + return await progress2.race(this._evaluateExpressionHandle(expression2, options, arg2)); + } + async getProperty(progress2, propertyName) { + return await progress2.race(this._getProperty(propertyName)); + } + async getProperties(progress2) { + return await progress2.race(this.internalGetProperties()); + } + async jsonValue(progress2) { + return await progress2.race(this._jsonValue()); + } + async evaluate(pageFunction, arg2) { + return evaluate(this._context, true, pageFunction, this, arg2); + } + async evaluateHandle(pageFunction, arg2) { + return evaluate(this._context, false, pageFunction, this, arg2); + } + async internalEvaluateExpression(expression2, options, arg2) { + return await evaluateExpression(this._context, expression2, { ...options, returnByValue: true }, this, arg2); + } + async _evaluateExpressionHandle(expression2, options, arg2) { + return await evaluateExpression(this._context, expression2, { ...options, returnByValue: false }, this, arg2); + } + async _getProperty(propertyName) { + const objectHandle = await this.evaluateHandle((object, propertyName2) => { + const result3 = { __proto__: null }; + result3[propertyName2] = object[propertyName2]; + return result3; + }, propertyName); + const properties = await objectHandle.internalGetProperties(); + const result2 = properties.get(propertyName); + objectHandle.dispose(); + return result2; + } + async internalGetProperties() { + if (!this._objectId) + return /* @__PURE__ */ new Map(); + return this._context.getProperties(this); + } + rawValue() { + return this._value; + } + async _jsonValue() { + if (!this._objectId) + return this._value; + const script = `(utilityScript, ...args) => utilityScript.jsonValue(...args)`; + return this._context._evaluateWithArguments(script, true, [true], [this]); + } + asElement() { + return null; + } + dispose() { + if (this._disposed) + return; + this._disposed = true; + if (this._objectId) { + this._context._releaseHandle(this).catch((e) => { + }); + if (globalThis.leakedJSHandles) + globalThis.leakedJSHandles.delete(this); + } + } + [Symbol.dispose]() { + this.dispose(); + } + toString() { + return this._preview; + } + _setPreviewCallback(callback) { + this._previewCallback = callback; + } + preview() { + return this._preview; + } + worldNameForTest() { + return this._context.worldNameForTest; + } + _setPreview(preview) { + this._preview = preview; + if (this._previewCallback) + this._previewCallback(preview); + } + }; + JavaScriptErrorInEvaluate = class extends Error { + }; + snapshottedFunctionBuiltins = [ + // DOM + "Node", + "Element", + "NodeFilter", + "HTMLElement", + "Document", + "ShadowRoot", + "MutationObserver", + "Event", + "CustomEvent", + "EventTarget", + // JS standard + "Map", + "Set", + "WeakMap", + "WeakSet", + "Promise", + "Symbol", + "Error", + "TypeError", + "RegExp", + "Array", + "Object" + ]; + snapshottedObjectBuiltins = ["JSON", "Math"]; + snapshottedTimerBuiltins = ["setTimeout"]; + saveGlobalsSnapshotSource = `window.__pwSnapshotGlobals = { +${[...snapshottedFunctionBuiltins, ...snapshottedObjectBuiltins, ...snapshottedTimerBuiltins].map((n) => ` ${n}: window.${n}`).join(",\n")} +};`; + mainWorldGlobalsSnapshotSource = ` + const __snap = globalThis.__pwSnapshotGlobals || {}; +${snapshottedFunctionBuiltins.map((n) => ` const ${n} = (typeof globalThis.${n} === 'function' ? globalThis.${n} : __snap.${n});`).join("\n")} +${snapshottedObjectBuiltins.map((n) => ` const ${n} = (typeof globalThis.${n} === 'object' && globalThis.${n} ? globalThis.${n} : __snap.${n});`).join("\n")} +`; + } +}); + +// packages/playwright-core/src/server/fileUploadUtils.ts +async function filesExceedUploadLimit(files) { + const sizes = await Promise.all(files.map(async (file) => (await import_fs12.default.promises.stat(file)).size)); + return sizes.reduce((total, size) => total + size, 0) >= fileUploadSizeLimit; +} +async function prepareFilesForUpload(frame, params2) { + const { payloads, streams, directoryStream } = params2; + let { localPaths, localDirectory } = params2; + if (localPaths && !frame.attribution.playwright.options.isClientCollocatedWithServer) + throw new Error("localPaths are not allowed when the client is not local"); + if ([payloads, localPaths, localDirectory, streams, directoryStream].filter(Boolean).length !== 1) + throw new Error("Exactly one of payloads, localPaths and streams must be provided"); + if (streams) + localPaths = streams.map((c) => c.path()); + if (directoryStream) + localDirectory = directoryStream.path(); + if (localPaths) { + for (const p of localPaths) + assert(import_path12.default.isAbsolute(p) && import_path12.default.resolve(p) === p, "Paths provided to localPaths must be absolute and fully resolved."); + } + let fileBuffers = payloads; + if (!frame._page.browserContext._browser._isBrowserCollocatedWithServer) { + if (localPaths) { + if (await filesExceedUploadLimit(localPaths)) + throw new Error("Cannot transfer files larger than 50Mb to a browser not co-located with the server"); + fileBuffers = await Promise.all(localPaths.map(async (item) => { + return { + name: import_path12.default.basename(item), + buffer: await import_fs12.default.promises.readFile(item), + lastModifiedMs: (await import_fs12.default.promises.stat(item)).mtimeMs + }; + })); + localPaths = void 0; + } + } + const filePayloads = fileBuffers?.map((payload) => ({ + name: payload.name, + mimeType: payload.mimeType || mime4.getType(payload.name) || "application/octet-stream", + buffer: payload.buffer.toString("base64"), + lastModifiedMs: payload.lastModifiedMs + })); + return { localPaths, localDirectory, filePayloads }; +} +var import_fs12, import_path12, mime4, fileUploadSizeLimit; +var init_fileUploadUtils = __esm({ + "packages/playwright-core/src/server/fileUploadUtils.ts"() { + "use strict"; + import_fs12 = __toESM(require("fs")); + import_path12 = __toESM(require("path")); + init_assert(); + mime4 = require("./utilsBundle").mime; + fileUploadSizeLimit = 50 * 1024 * 1024; + } +}); + +// packages/playwright-core/src/generated/injectedScriptSource.ts +var source5; +var init_injectedScriptSource = __esm({ + "packages/playwright-core/src/generated/injectedScriptSource.ts"() { + "use strict"; + source5 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/injectedScript.ts\nvar injectedScript_exports = {};\n__export(injectedScript_exports, {\n InjectedScript: () => InjectedScript\n});\nmodule.exports = __toCommonJS(injectedScript_exports);\n\n// packages/isomorphic/ariaSnapshot.ts\nfunction hasPointerCursor(ariaNode) {\n return ariaNode.box.cursor === "pointer";\n}\nfunction parseAriaSnapshot(yaml, text, options = {}) {\n var _a;\n const lineCounter = new yaml.LineCounter();\n const parseOptions = {\n keepSourceTokens: true,\n lineCounter,\n ...options\n };\n const yamlDoc = yaml.parseDocument(text, parseOptions);\n const errors = [];\n const convertRange = (range) => {\n return [lineCounter.linePos(range[0]), lineCounter.linePos(range[1])];\n };\n const addError = (error) => {\n errors.push({\n message: error.message,\n range: [lineCounter.linePos(error.pos[0]), lineCounter.linePos(error.pos[1])]\n });\n };\n const convertSeq = (container, seq) => {\n for (const item of seq.items) {\n const itemIsString = item instanceof yaml.Scalar && typeof item.value === "string";\n if (itemIsString) {\n const childNode = KeyParser.parse(item, parseOptions, errors);\n if (childNode) {\n container.children = container.children || [];\n container.children.push(childNode);\n }\n continue;\n }\n const itemIsMap = item instanceof yaml.YAMLMap;\n if (itemIsMap) {\n convertMap(container, item);\n continue;\n }\n errors.push({\n message: "Sequence items should be strings or maps",\n range: convertRange(item.range || seq.range)\n });\n }\n };\n const convertMap = (container, map) => {\n var _a2;\n for (const entry of map.items) {\n container.children = container.children || [];\n const keyIsString = entry.key instanceof yaml.Scalar && typeof entry.key.value === "string";\n if (!keyIsString) {\n errors.push({\n message: "Only string keys are supported",\n range: convertRange(entry.key.range || map.range)\n });\n continue;\n }\n const key = entry.key;\n const value = entry.value;\n if (key.value === "text") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Text value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n kind: "text",\n text: textValue(value.value)\n });\n continue;\n }\n if (key.value === "/children") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString || value.value !== "contain" && value.value !== "equal" && value.value !== "deep-equal") {\n errors.push({\n message: \'Strict value should be "contain", "equal" or "deep-equal"\',\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.containerMode = value.value;\n continue;\n }\n if (key.value.startsWith("/")) {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Property value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.props = (_a2 = container.props) != null ? _a2 : {};\n container.props[key.value.slice(1)] = textValue(value.value);\n continue;\n }\n const childNode = KeyParser.parse(key, parseOptions, errors);\n if (!childNode)\n continue;\n const valueIsScalar = value instanceof yaml.Scalar;\n if (valueIsScalar) {\n const type = typeof value.value;\n if (type !== "string" && type !== "number" && type !== "boolean") {\n errors.push({\n message: "Node value should be a string or a sequence",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n ...childNode,\n children: [{\n kind: "text",\n text: textValue(String(value.value))\n }]\n });\n continue;\n }\n const valueIsSequence = value instanceof yaml.YAMLSeq;\n if (valueIsSequence) {\n container.children.push(childNode);\n convertSeq(childNode, value);\n continue;\n }\n errors.push({\n message: "Map values should be strings or sequences",\n range: convertRange(entry.value.range || map.range)\n });\n }\n };\n const fragment = { kind: "role", role: "fragment" };\n yamlDoc.errors.forEach(addError);\n if (errors.length)\n return { errors, fragment };\n if (!(yamlDoc.contents instanceof yaml.YAMLSeq)) {\n errors.push({\n message: \'Aria snapshot must be a YAML sequence, elements starting with " -"\',\n range: yamlDoc.contents ? convertRange(yamlDoc.contents.range) : [{ line: 0, col: 0 }, { line: 0, col: 0 }]\n });\n }\n if (errors.length)\n return { errors, fragment };\n convertSeq(fragment, yamlDoc.contents);\n if (errors.length)\n return { errors, fragment: emptyFragment };\n if (((_a = fragment.children) == null ? void 0 : _a.length) === 1 && (!fragment.containerMode || fragment.containerMode === "contain"))\n return { fragment: fragment.children[0], errors: [] };\n return { fragment, errors: [] };\n}\nvar emptyFragment = { kind: "role", role: "fragment" };\nfunction normalizeWhitespace(text) {\n return text.replace(/[\\u200b\\u00ad]/g, "").replace(/[\\r\\n\\s\\t]+/g, " ").trim();\n}\nfunction textValue(value) {\n return {\n raw: value,\n normalized: normalizeWhitespace(value)\n };\n}\nvar KeyParser = class _KeyParser {\n static parse(text, options, errors) {\n try {\n return new _KeyParser(text.value)._parse();\n } catch (e) {\n if (e instanceof ParserError) {\n const message = options.prettyErrors === false ? e.message : e.message + ":\\n\\n" + text.value + "\\n" + " ".repeat(e.pos) + "^\\n";\n errors.push({\n message,\n range: [options.lineCounter.linePos(text.range[0]), options.lineCounter.linePos(text.range[0] + e.pos)]\n });\n return null;\n }\n throw e;\n }\n }\n constructor(input) {\n this._input = input;\n this._pos = 0;\n this._length = input.length;\n }\n _peek() {\n return this._input[this._pos] || "";\n }\n _next() {\n if (this._pos < this._length)\n return this._input[this._pos++];\n return null;\n }\n _eof() {\n return this._pos >= this._length;\n }\n _isWhitespace() {\n return !this._eof() && /\\s/.test(this._peek());\n }\n _skipWhitespace() {\n while (this._isWhitespace())\n this._pos++;\n }\n _readIdentifier(type) {\n if (this._eof())\n this._throwError(`Unexpected end of input when expecting ${type}`);\n const start = this._pos;\n while (!this._eof() && /[a-zA-Z]/.test(this._peek()))\n this._pos++;\n return this._input.slice(start, this._pos);\n }\n _readString() {\n let result = "";\n let escaped = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n } else if (ch === \'"\') {\n return result;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated string");\n }\n _throwError(message, offset = 0) {\n throw new ParserError(message, offset || this._pos);\n }\n _readRegex() {\n let result = "";\n let escaped = false;\n let insideClass = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n result += ch;\n } else if (ch === "/" && !insideClass) {\n return { pattern: result };\n } else if (ch === "[") {\n insideClass = true;\n result += ch;\n } else if (ch === "]" && insideClass) {\n result += ch;\n insideClass = false;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated regex");\n }\n _readStringOrRegex() {\n const ch = this._peek();\n if (ch === \'"\') {\n this._next();\n return normalizeWhitespace(this._readString());\n }\n if (ch === "/") {\n this._next();\n return this._readRegex();\n }\n return null;\n }\n _readAttributes(result) {\n let errorPos = this._pos;\n while (true) {\n this._skipWhitespace();\n if (this._peek() === "[") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n const flagName = this._readIdentifier("attribute");\n this._skipWhitespace();\n let flagValue = "";\n if (this._peek() === "=") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n while (this._peek() !== "]" && !this._isWhitespace() && !this._eof())\n flagValue += this._next();\n }\n this._skipWhitespace();\n if (this._peek() !== "]")\n this._throwError("Expected ]");\n this._next();\n this._applyAttribute(result, flagName, flagValue || "true", errorPos);\n } else {\n break;\n }\n }\n }\n _parse() {\n this._skipWhitespace();\n const role = this._readIdentifier("role");\n this._skipWhitespace();\n const name = this._readStringOrRegex() || "";\n const result = { kind: "role", role, name };\n this._readAttributes(result);\n this._skipWhitespace();\n if (!this._eof())\n this._throwError("Unexpected input");\n return result;\n }\n _applyAttribute(node, key, value, errorPos) {\n if (key === "checked") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "checked" attribute must be a boolean or "mixed"\', errorPos);\n node.checked = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "disabled") {\n this._assert(value === "true" || value === "false", \'Value of "disabled" attribute must be a boolean\', errorPos);\n node.disabled = value === "true";\n return;\n }\n if (key === "expanded") {\n this._assert(value === "true" || value === "false", \'Value of "expanded" attribute must be a boolean\', errorPos);\n node.expanded = value === "true";\n return;\n }\n if (key === "active") {\n this._assert(value === "true" || value === "false", \'Value of "active" attribute must be a boolean\', errorPos);\n node.active = value === "true";\n return;\n }\n if (key === "invalid") {\n this._assert(value === "true" || value === "false" || value === "grammar" || value === "spelling", \'Value of "invalid" attribute must be a boolean, "grammar" or "spelling"\', errorPos);\n node.invalid = value === "true" ? true : value === "false" ? false : value;\n return;\n }\n if (key === "level") {\n this._assert(!isNaN(Number(value)), \'Value of "level" attribute must be a number\', errorPos);\n node.level = Number(value);\n return;\n }\n if (key === "pressed") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "pressed" attribute must be a boolean or "mixed"\', errorPos);\n node.pressed = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "selected") {\n this._assert(value === "true" || value === "false", \'Value of "selected" attribute must be a boolean\', errorPos);\n node.selected = value === "true";\n return;\n }\n this._assert(false, `Unsupported attribute [${key}]`, errorPos);\n }\n _assert(value, message, valuePos) {\n if (!value)\n this._throwError(message || "Assertion error", valuePos);\n }\n};\nvar ParserError = class extends Error {\n constructor(message, pos) {\n super(message);\n this.pos = pos;\n }\n};\nfunction findNewNode(from, to) {\n var _a, _b;\n function fillMap(root, map, position) {\n let size = 1;\n let childPosition = position + size;\n for (const child of root.children || []) {\n if (typeof child === "string") {\n size++;\n childPosition++;\n } else {\n size += fillMap(child, map, childPosition);\n childPosition += size;\n }\n }\n if (!["none", "presentation", "fragment", "iframe", "generic"].includes(root.role) && root.name) {\n let byRole = map.get(root.role);\n if (!byRole) {\n byRole = /* @__PURE__ */ new Map();\n map.set(root.role, byRole);\n }\n const existing = byRole.get(root.name);\n const sizeAndPosition = size * 100 - position;\n if (!existing || existing.sizeAndPosition < sizeAndPosition)\n byRole.set(root.name, { node: root, sizeAndPosition });\n }\n return size;\n }\n const fromMap = /* @__PURE__ */ new Map();\n if (from)\n fillMap(from, fromMap, 0);\n const toMap = /* @__PURE__ */ new Map();\n fillMap(to, toMap, 0);\n const result = [];\n for (const [role, byRole] of toMap) {\n for (const [name, byName] of byRole) {\n const inFrom = (_a = fromMap.get(role)) == null ? void 0 : _a.get(name);\n if (!inFrom)\n result.push(byName);\n }\n }\n result.sort((a, b) => b.sizeAndPosition - a.sizeAndPosition);\n return (_b = result[0]) == null ? void 0 : _b.node;\n}\n\n// packages/isomorphic/stringUtils.ts\nfunction escapeWithQuotes(text, char = "\'") {\n const stringified = JSON.stringify(text);\n const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\\\"/g, \'"\');\n if (char === "\'")\n return char + escapedText.replace(/[\']/g, "\\\\\'") + char;\n if (char === \'"\')\n return char + escapedText.replace(/["]/g, \'\\\\"\') + char;\n if (char === "`")\n return char + escapedText.replace(/[`]/g, "\\\\`") + char;\n throw new Error("Invalid escape char");\n}\nfunction toTitleCase(name) {\n return name.charAt(0).toUpperCase() + name.substring(1);\n}\nfunction toSnakeCase(name) {\n return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();\n}\nfunction quoteCSSAttributeValue(text) {\n return `"${text.replace(/["\\\\]/g, (char) => "\\\\" + char)}"`;\n}\nvar normalizedWhitespaceCache;\nfunction cacheNormalizedWhitespaces() {\n normalizedWhitespaceCache = /* @__PURE__ */ new Map();\n}\nfunction normalizeWhiteSpace(text) {\n let result = normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.get(text);\n if (result === void 0) {\n result = text.replace(/[\\u200b\\u00ad]/g, "").trim().replace(/\\s+/g, " ");\n normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.set(text, result);\n }\n return result;\n}\nfunction normalizeEscapedRegexQuotes(source) {\n return source.replace(/(^|[^\\\\])(\\\\\\\\)*\\\\([\'"`])/g, "$1$2$3");\n}\nfunction escapeRegexForSelector(re) {\n if (re.unicode || re.unicodeSets)\n return String(re);\n return String(re).replace(/(^|[^\\\\])(\\\\\\\\)*(["\'`])/g, "$1$2\\\\$3").replace(/>>/g, "\\\\>\\\\>");\n}\nfunction escapeForTextSelector(text, exact) {\n if (typeof text !== "string")\n return escapeRegexForSelector(text);\n return `${JSON.stringify(text)}${exact ? "s" : "i"}`;\n}\nfunction escapeForAttributeSelector(value, exact) {\n if (typeof value !== "string")\n return escapeRegexForSelector(value);\n return `"${value.replace(/\\\\/g, "\\\\\\\\").replace(/["]/g, \'\\\\"\')}"${exact ? "s" : "i"}`;\n}\nfunction trimString(input, cap, suffix = "") {\n if (input.length <= cap)\n return input;\n const chars = [...input];\n if (chars.length > cap)\n return chars.slice(0, cap - suffix.length).join("") + suffix;\n return chars.join("");\n}\nfunction trimStringWithEllipsis(input, cap) {\n return trimString(input, cap, "\\u2026");\n}\nfunction truncateDataUrl(url) {\n if (!url.startsWith("data:"))\n return url;\n const comma = url.indexOf(",");\n if (comma === -1)\n return url;\n return url.slice(0, comma + 1) + "\\u2026";\n}\nfunction escapeRegExp(s) {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");\n}\nfunction longestCommonSubstring(s1, s2) {\n const n = s1.length;\n const m = s2.length;\n let maxLen = 0;\n let endingIndex = 0;\n const dp = Array(n + 1).fill(null).map(() => Array(m + 1).fill(0));\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (s1[i - 1] === s2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n if (dp[i][j] > maxLen) {\n maxLen = dp[i][j];\n endingIndex = i;\n }\n }\n }\n }\n return s1.slice(endingIndex - maxLen, endingIndex);\n}\nvar ansiRegex = new RegExp("([\\\\u001B\\\\u009B][[\\\\]()#?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)|(?:(?:\\\\d{0,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~])))", "g");\n\n// packages/isomorphic/yaml.ts\nfunction yamlEscapeKeyIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return `\'` + str.replace(/\'/g, `\'\'`) + `\'`;\n}\nfunction yamlEscapeValueIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return \'"\' + str.replace(/[\\\\"\\x00-\\x1f\\x7f-\\x9f]/g, (c) => {\n switch (c) {\n case "\\\\":\n return "\\\\\\\\";\n case \'"\':\n return \'\\\\"\';\n case "\\b":\n return "\\\\b";\n case "\\f":\n return "\\\\f";\n case "\\n":\n return "\\\\n";\n case "\\r":\n return "\\\\r";\n case " ":\n return "\\\\t";\n default:\n const code = c.charCodeAt(0);\n return "\\\\x" + code.toString(16).padStart(2, "0");\n }\n }) + \'"\';\n}\nfunction yamlStringNeedsQuotes(str) {\n if (str.length === 0)\n return true;\n if (/^\\s|\\s$/.test(str))\n return true;\n if (/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f]/.test(str))\n return true;\n if (/^-/.test(str))\n return true;\n if (/[\\n:](\\s|$)/.test(str))\n return true;\n if (/\\s#/.test(str))\n return true;\n if (/[\\n\\r]/.test(str))\n return true;\n if (/^[&*\\],?!>|@"\'#%]/.test(str))\n return true;\n if (/[{}`]/.test(str))\n return true;\n if (/^\\[/.test(str))\n return true;\n if (!isNaN(Number(str)) || ["y", "n", "yes", "no", "true", "false", "on", "off", "null"].includes(str.toLowerCase()))\n return true;\n return false;\n}\n\n// packages/isomorphic/ariaSnapshotRenderer.ts\nfunction renderAriaSnapshotAsYaml(snapshot, options = {}) {\n const lines = [];\n const includeText = options.convertStringsToRegex ? textContributesInfo : () => true;\n const renderString = options.convertStringsToRegex ? convertToBestGuessRegex : (str) => str;\n const visitText = (text, depth) => {\n const escaped = yamlEscapeValueIfNeeded(renderString(text));\n if (escaped)\n lines.push(indent(depth) + "- text: " + escaped);\n };\n const createKey = (node) => {\n let key = node.role;\n if (node.name && node.name.length <= 900) {\n const name = renderString(node.name);\n if (name) {\n const isRegex = options.convertStringsToRegex && name !== node.name;\n key += " " + (isRegex ? name : JSON.stringify(name));\n }\n }\n if (node.checked === "mixed")\n key += ` [checked=mixed]`;\n if (node.checked === true)\n key += ` [checked]`;\n if (node.disabled)\n key += ` [disabled]`;\n if (node.expanded)\n key += ` [expanded]`;\n if (node.active)\n key += ` [active]`;\n if (node.invalid === "grammar" || node.invalid === "spelling")\n key += ` [invalid=${node.invalid}]`;\n if (node.invalid === true)\n key += ` [invalid]`;\n if (node.level)\n key += ` [level=${node.level}]`;\n if (node.pressed === "mixed")\n key += ` [pressed=mixed]`;\n if (node.pressed === true)\n key += ` [pressed]`;\n if (node.selected === true)\n key += ` [selected]`;\n if (node.ariaHidden)\n key += ` [aria-hidden]`;\n if (node.ref) {\n key += ` [ref=${node.ref}]`;\n if (node.cursor === "pointer")\n key += " [cursor=pointer]";\n }\n if (node.box)\n key += ` [box=${node.box.x},${node.box.y},${node.box.width},${node.box.height}]`;\n return key;\n };\n const visit = (node, depth) => {\n var _a, _b;\n if (node.role === "text") {\n visitText(node.text || "", depth);\n return;\n }\n (_a = options.lineToNode) == null ? void 0 : _a.set(lines.length, node);\n const escapedKey = indent(depth) + "- " + yamlEscapeKeyIfNeeded(createKey(node));\n const props = [];\n if (node.url !== void 0)\n props.push(["url", node.url]);\n if (node.placeholder !== void 0)\n props.push(["placeholder", node.placeholder]);\n if (node.text === void 0 && !props.length && !((_b = node.children) == null ? void 0 : _b.length)) {\n lines.push(escapedKey);\n } else if (node.text !== void 0 && !props.length) {\n if (includeText(node, node.text))\n lines.push(escapedKey + ": " + yamlEscapeValueIfNeeded(renderString(node.text)));\n else\n lines.push(escapedKey);\n } else {\n lines.push(escapedKey + ":");\n for (const [name, value] of props)\n lines.push(indent(depth + 1) + "- /" + name + ": " + yamlEscapeValueIfNeeded(value));\n if (node.text !== void 0) {\n visitText(includeText(node, node.text) ? node.text : "", depth + 1);\n } else {\n for (const child of node.children || []) {\n if (typeof child === "string")\n visitText(includeText(node, child) ? child : "", depth + 1);\n else\n visit(child, depth + 1);\n }\n }\n }\n };\n for (const node of snapshot)\n visit(node, 0);\n return lines.join("\\n");\n}\nfunction indent(depth) {\n return " ".repeat(depth);\n}\nfunction convertToBestGuessRegex(text) {\n const dynamicContent = [\n // 550e8400-e29b-41d4-a716-446655440000\n { regex: /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/, replacement: "[0-9a-fA-F-]+" },\n // 2mb\n { regex: /\\b[\\d,.]+[bkmBKM]+\\b/, replacement: "[\\\\d,.]+[bkmBKM]+" },\n // 2ms, 20s\n { regex: /\\b\\d+[hmsp]+\\b/, replacement: "\\\\d+[hmsp]+" },\n { regex: /\\b[\\d,.]+[hmsp]+\\b/, replacement: "[\\\\d,.]+[hmsp]+" },\n // Do not replace single digits with regex by default.\n // 2+ digits: [Issue 22, 22.3, 2.33, 2,333]\n { regex: /\\b\\d+,\\d+\\b/, replacement: "\\\\d+,\\\\d+" },\n { regex: /\\b\\d+\\.\\d{2,}\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\.\\d+\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\b/, replacement: "\\\\d+" }\n ];\n let pattern = "";\n let lastIndex = 0;\n const combinedRegex = new RegExp(dynamicContent.map((r) => "(" + r.regex.source + ")").join("|"), "g");\n text.replace(combinedRegex, (match, ...args) => {\n const offset = args[args.length - 2];\n const groups = args.slice(0, -2);\n pattern += escapeRegExp(text.slice(lastIndex, offset));\n for (let i = 0; i < groups.length; i++) {\n if (groups[i]) {\n const { replacement } = dynamicContent[i];\n pattern += replacement;\n break;\n }\n }\n lastIndex = offset + match.length;\n return match;\n });\n if (!pattern)\n return text;\n pattern += escapeRegExp(text.slice(lastIndex));\n return String(new RegExp(pattern));\n}\nfunction textContributesInfo(node, text) {\n if (!text.length)\n return false;\n if (!node.name)\n return true;\n const substr = text.length <= 200 && node.name.length <= 200 ? longestCommonSubstring(text, node.name) : "";\n let filtered = text;\n while (substr && filtered.includes(substr))\n filtered = filtered.replace(substr, "");\n return filtered.trim().length / text.length > 0.1;\n}\n\n// packages/isomorphic/cssTokenizer.ts\nvar between = function(num, first, last) {\n return num >= first && num <= last;\n};\nfunction digit(code) {\n return between(code, 48, 57);\n}\nfunction hexdigit(code) {\n return digit(code) || between(code, 65, 70) || between(code, 97, 102);\n}\nfunction uppercaseletter(code) {\n return between(code, 65, 90);\n}\nfunction lowercaseletter(code) {\n return between(code, 97, 122);\n}\nfunction letter(code) {\n return uppercaseletter(code) || lowercaseletter(code);\n}\nfunction nonascii(code) {\n return code >= 128;\n}\nfunction namestartchar(code) {\n return letter(code) || nonascii(code) || code === 95;\n}\nfunction namechar(code) {\n return namestartchar(code) || digit(code) || code === 45;\n}\nfunction nonprintable(code) {\n return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127;\n}\nfunction newline(code) {\n return code === 10;\n}\nfunction whitespace(code) {\n return newline(code) || code === 9 || code === 32;\n}\nvar maximumallowedcodepoint = 1114111;\nvar InvalidCharacterError = class extends Error {\n constructor(message) {\n super(message);\n this.name = "InvalidCharacterError";\n }\n};\nfunction preprocess(str) {\n const codepoints = [];\n for (let i = 0; i < str.length; i++) {\n let code = str.charCodeAt(i);\n if (code === 13 && str.charCodeAt(i + 1) === 10) {\n code = 10;\n i++;\n }\n if (code === 13 || code === 12)\n code = 10;\n if (code === 0)\n code = 65533;\n if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) {\n const lead = code - 55296;\n const trail = str.charCodeAt(i + 1) - 56320;\n code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail;\n i++;\n }\n codepoints.push(code);\n }\n return codepoints;\n}\nfunction stringFromCode(code) {\n if (code <= 65535)\n return String.fromCharCode(code);\n code -= Math.pow(2, 16);\n const lead = Math.floor(code / Math.pow(2, 10)) + 55296;\n const trail = code % Math.pow(2, 10) + 56320;\n return String.fromCharCode(lead) + String.fromCharCode(trail);\n}\nfunction tokenize(str1) {\n const str = preprocess(str1);\n let i = -1;\n const tokens = [];\n let code;\n let line = 0;\n let column = 0;\n let lastLineLength = 0;\n const incrLineno = function() {\n line += 1;\n lastLineLength = column;\n column = 0;\n };\n const locStart = { line, column };\n const codepoint = function(i2) {\n if (i2 >= str.length)\n return -1;\n return str[i2];\n };\n const next = function(num) {\n if (num === void 0)\n num = 1;\n if (num > 3)\n throw "Spec Error: no more than three codepoints of lookahead.";\n return codepoint(i + num);\n };\n const consume = function(num) {\n if (num === void 0)\n num = 1;\n i += num;\n code = codepoint(i);\n if (newline(code))\n incrLineno();\n else\n column += num;\n return true;\n };\n const reconsume = function() {\n i -= 1;\n if (newline(code)) {\n line -= 1;\n column = lastLineLength;\n } else {\n column -= 1;\n }\n locStart.line = line;\n locStart.column = column;\n return true;\n };\n const eof = function(codepoint2) {\n if (codepoint2 === void 0)\n codepoint2 = code;\n return codepoint2 === -1;\n };\n const donothing = function() {\n };\n const parseerror = function() {\n };\n const consumeAToken = function() {\n consumeComments();\n consume();\n if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n return new WhitespaceToken();\n } else if (code === 34) {\n return consumeAStringToken();\n } else if (code === 35) {\n if (namechar(next()) || areAValidEscape(next(1), next(2))) {\n const token = new HashToken("");\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n token.type = "id";\n token.value = consumeAName();\n return token;\n } else {\n return new DelimToken(code);\n }\n } else if (code === 36) {\n if (next() === 61) {\n consume();\n return new SuffixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 39) {\n return consumeAStringToken();\n } else if (code === 40) {\n return new OpenParenToken();\n } else if (code === 41) {\n return new CloseParenToken();\n } else if (code === 42) {\n if (next() === 61) {\n consume();\n return new SubstringMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 43) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 44) {\n return new CommaToken();\n } else if (code === 45) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else if (next(1) === 45 && next(2) === 62) {\n consume(2);\n return new CDCToken();\n } else if (startsWithAnIdentifier()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 46) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 58) {\n return new ColonToken();\n } else if (code === 59) {\n return new SemicolonToken();\n } else if (code === 60) {\n if (next(1) === 33 && next(2) === 45 && next(3) === 45) {\n consume(3);\n return new CDOToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 64) {\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n return new AtKeywordToken(consumeAName());\n else\n return new DelimToken(code);\n } else if (code === 91) {\n return new OpenSquareToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n parseerror();\n return new DelimToken(code);\n }\n } else if (code === 93) {\n return new CloseSquareToken();\n } else if (code === 94) {\n if (next() === 61) {\n consume();\n return new PrefixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 123) {\n return new OpenCurlyToken();\n } else if (code === 124) {\n if (next() === 61) {\n consume();\n return new DashMatchToken();\n } else if (next() === 124) {\n consume();\n return new ColumnToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 125) {\n return new CloseCurlyToken();\n } else if (code === 126) {\n if (next() === 61) {\n consume();\n return new IncludeMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (digit(code)) {\n reconsume();\n return consumeANumericToken();\n } else if (namestartchar(code)) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else if (eof()) {\n return new EOFToken();\n } else {\n return new DelimToken(code);\n }\n };\n const consumeComments = function() {\n while (next(1) === 47 && next(2) === 42) {\n consume(2);\n while (true) {\n consume();\n if (code === 42 && next() === 47) {\n consume();\n break;\n } else if (eof()) {\n parseerror();\n return;\n }\n }\n }\n };\n const consumeANumericToken = function() {\n const num = consumeANumber();\n if (wouldStartAnIdentifier(next(1), next(2), next(3))) {\n const token = new DimensionToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n token.unit = consumeAName();\n return token;\n } else if (next() === 37) {\n consume();\n const token = new PercentageToken();\n token.value = num.value;\n token.repr = num.repr;\n return token;\n } else {\n const token = new NumberToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n return token;\n }\n };\n const consumeAnIdentlikeToken = function() {\n const str2 = consumeAName();\n if (str2.toLowerCase() === "url" && next() === 40) {\n consume();\n while (whitespace(next(1)) && whitespace(next(2)))\n consume();\n if (next() === 34 || next() === 39)\n return new FunctionToken(str2);\n else if (whitespace(next()) && (next(2) === 34 || next(2) === 39))\n return new FunctionToken(str2);\n else\n return consumeAURLToken();\n } else if (next() === 40) {\n consume();\n return new FunctionToken(str2);\n } else {\n return new IdentToken(str2);\n }\n };\n const consumeAStringToken = function(endingCodePoint) {\n if (endingCodePoint === void 0)\n endingCodePoint = code;\n let string = "";\n while (consume()) {\n if (code === endingCodePoint || eof()) {\n return new StringToken(string);\n } else if (newline(code)) {\n parseerror();\n reconsume();\n return new BadStringToken();\n } else if (code === 92) {\n if (eof(next()))\n donothing();\n else if (newline(next()))\n consume();\n else\n string += stringFromCode(consumeEscape());\n } else {\n string += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeAURLToken = function() {\n const token = new URLToken("");\n while (whitespace(next()))\n consume();\n if (eof(next()))\n return token;\n while (consume()) {\n if (code === 41 || eof()) {\n return token;\n } else if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n if (next() === 41 || eof(next())) {\n consume();\n return token;\n } else {\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n token.value += stringFromCode(consumeEscape());\n } else {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else {\n token.value += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeEscape = function() {\n consume();\n if (hexdigit(code)) {\n const digits = [code];\n for (let total = 0; total < 5; total++) {\n if (hexdigit(next())) {\n consume();\n digits.push(code);\n } else {\n break;\n }\n }\n if (whitespace(next()))\n consume();\n let value = parseInt(digits.map(function(x) {\n return String.fromCharCode(x);\n }).join(""), 16);\n if (value > maximumallowedcodepoint)\n value = 65533;\n return value;\n } else if (eof()) {\n return 65533;\n } else {\n return code;\n }\n };\n const areAValidEscape = function(c1, c2) {\n if (c1 !== 92)\n return false;\n if (newline(c2))\n return false;\n return true;\n };\n const startsWithAValidEscape = function() {\n return areAValidEscape(code, next());\n };\n const wouldStartAnIdentifier = function(c1, c2, c3) {\n if (c1 === 45)\n return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3);\n else if (namestartchar(c1))\n return true;\n else if (c1 === 92)\n return areAValidEscape(c1, c2);\n else\n return false;\n };\n const startsWithAnIdentifier = function() {\n return wouldStartAnIdentifier(code, next(1), next(2));\n };\n const wouldStartANumber = function(c1, c2, c3) {\n if (c1 === 43 || c1 === 45) {\n if (digit(c2))\n return true;\n if (c2 === 46 && digit(c3))\n return true;\n return false;\n } else if (c1 === 46) {\n if (digit(c2))\n return true;\n return false;\n } else if (digit(c1)) {\n return true;\n } else {\n return false;\n }\n };\n const startsWithANumber = function() {\n return wouldStartANumber(code, next(1), next(2));\n };\n const consumeAName = function() {\n let result = "";\n while (consume()) {\n if (namechar(code)) {\n result += stringFromCode(code);\n } else if (startsWithAValidEscape()) {\n result += stringFromCode(consumeEscape());\n } else {\n reconsume();\n return result;\n }\n }\n throw new Error("Internal parse error");\n };\n const consumeANumber = function() {\n let repr = "";\n let type = "integer";\n if (next() === 43 || next() === 45) {\n consume();\n repr += stringFromCode(code);\n }\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n if (next(1) === 46 && digit(next(2))) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const c1 = next(1);\n const c2 = next(2);\n const c3 = next(3);\n if ((c1 === 69 || c1 === 101) && digit(c2)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const value = convertAStringToANumber(repr);\n return { type, value, repr };\n };\n const convertAStringToANumber = function(string) {\n return +string;\n };\n const consumeTheRemnantsOfABadURL = function() {\n while (consume()) {\n if (code === 41 || eof()) {\n return;\n } else if (startsWithAValidEscape()) {\n consumeEscape();\n donothing();\n } else {\n donothing();\n }\n }\n };\n let iterationCount = 0;\n while (!eof(next())) {\n tokens.push(consumeAToken());\n iterationCount++;\n if (iterationCount > str.length * 2)\n throw new Error("I\'m infinite-looping!");\n }\n return tokens;\n}\nvar CSSParserToken = class {\n constructor() {\n this.tokenType = "";\n }\n toJSON() {\n return { token: this.tokenType };\n }\n toString() {\n return this.tokenType;\n }\n toSource() {\n return "" + this;\n }\n};\nvar BadStringToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADSTRING";\n }\n};\nvar BadURLToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADURL";\n }\n};\nvar WhitespaceToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "WHITESPACE";\n }\n toString() {\n return "WS";\n }\n toSource() {\n return " ";\n }\n};\nvar CDOToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "CDO";\n }\n toSource() {\n return "";\n }\n};\nvar ColonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ":";\n }\n};\nvar SemicolonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ";";\n }\n};\nvar CommaToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ",";\n }\n};\nvar GroupingToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n this.mirror = "";\n }\n};\nvar OpenCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "{";\n this.value = "{";\n this.mirror = "}";\n }\n};\nvar CloseCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "}";\n this.value = "}";\n this.mirror = "{";\n }\n};\nvar OpenSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "[";\n this.value = "[";\n this.mirror = "]";\n }\n};\nvar CloseSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "]";\n this.value = "]";\n this.mirror = "[";\n }\n};\nvar OpenParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "(";\n this.value = "(";\n this.mirror = ")";\n }\n};\nvar CloseParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = ")";\n this.value = ")";\n this.mirror = "(";\n }\n};\nvar IncludeMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "~=";\n }\n};\nvar DashMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "|=";\n }\n};\nvar PrefixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "^=";\n }\n};\nvar SuffixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "$=";\n }\n};\nvar SubstringMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "*=";\n }\n};\nvar ColumnToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "||";\n }\n};\nvar EOFToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "EOF";\n }\n toSource() {\n return "";\n }\n};\nvar DelimToken = class extends CSSParserToken {\n constructor(code) {\n super();\n this.tokenType = "DELIM";\n this.value = "";\n this.value = stringFromCode(code);\n }\n toString() {\n return "DELIM(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n toSource() {\n if (this.value === "\\\\")\n return "\\\\\\n";\n else\n return this.value;\n }\n};\nvar StringValuedToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n }\n ASCIIMatch(str) {\n return this.value.toLowerCase() === str.toLowerCase();\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n};\nvar IdentToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "IDENT";\n this.value = val;\n }\n toString() {\n return "IDENT(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value);\n }\n};\nvar FunctionToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "FUNCTION";\n this.value = val;\n this.mirror = ")";\n }\n toString() {\n return "FUNCTION(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value) + "(";\n }\n};\nvar AtKeywordToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "AT-KEYWORD";\n this.value = val;\n }\n toString() {\n return "AT(" + this.value + ")";\n }\n toSource() {\n return "@" + escapeIdent(this.value);\n }\n};\nvar HashToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "HASH";\n this.value = val;\n this.type = "unrestricted";\n }\n toString() {\n return "HASH(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n return json;\n }\n toSource() {\n if (this.type === "id")\n return "#" + escapeIdent(this.value);\n else\n return "#" + escapeHash(this.value);\n }\n};\nvar StringToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "STRING";\n this.value = val;\n }\n toString() {\n return \'"\' + escapeString(this.value) + \'"\';\n }\n};\nvar URLToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "URL";\n this.value = val;\n }\n toString() {\n return "URL(" + this.value + ")";\n }\n toSource() {\n return \'url("\' + escapeString(this.value) + \'")\';\n }\n};\nvar NumberToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "NUMBER";\n this.type = "integer";\n this.repr = "";\n }\n toString() {\n if (this.type === "integer")\n return "INT(" + this.value + ")";\n return "NUMBER(" + this.value + ")";\n }\n toJSON() {\n const json = super.toJSON();\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr;\n }\n};\nvar PercentageToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "PERCENTAGE";\n this.repr = "";\n }\n toString() {\n return "PERCENTAGE(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr + "%";\n }\n};\nvar DimensionToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "DIMENSION";\n this.type = "integer";\n this.repr = "";\n this.unit = "";\n }\n toString() {\n return "DIM(" + this.value + "," + this.unit + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n json.unit = this.unit;\n return json;\n }\n toSource() {\n const source = this.repr;\n let unit = escapeIdent(this.unit);\n if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) {\n unit = "\\\\65 " + unit.slice(1, unit.length);\n }\n return source + unit;\n }\n};\nfunction escapeIdent(string) {\n string = "" + string;\n let result = "";\n const firstcode = string.charCodeAt(0);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45)\n result += "\\\\" + code.toString(16) + " ";\n else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + string[i];\n }\n return result;\n}\nfunction escapeHash(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + code.toString(16) + " ";\n }\n return result;\n}\nfunction escapeString(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127)\n result += "\\\\" + code.toString(16) + " ";\n else if (code === 34 || code === 92)\n result += "\\\\" + string[i];\n else\n result += string[i];\n }\n return result;\n}\n\n// packages/isomorphic/cssParser.ts\nvar InvalidSelectorError = class extends Error {\n};\nfunction parseCSS(selector, customNames) {\n let tokens;\n try {\n tokens = tokenize(selector);\n if (!(tokens[tokens.length - 1] instanceof EOFToken))\n tokens.push(new EOFToken());\n } catch (e) {\n const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`;\n const index = (e.stack || "").indexOf(e.message);\n if (index !== -1)\n e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length);\n e.message = newMessage;\n throw e;\n }\n const unsupportedToken = tokens.find((token) => {\n return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings.\n // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz }\n // Or this way :xpath( {complex-xpath-goes-here("hello")} )\n token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings?\n token instanceof URLToken || token instanceof PercentageToken;\n });\n if (unsupportedToken)\n throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n let pos = 0;\n const names = /* @__PURE__ */ new Set();\n function unexpected() {\n return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n }\n function skipWhitespace() {\n while (tokens[pos] instanceof WhitespaceToken)\n pos++;\n }\n function isIdent(p = pos) {\n return tokens[p] instanceof IdentToken;\n }\n function isString(p = pos) {\n return tokens[p] instanceof StringToken;\n }\n function isNumber(p = pos) {\n return tokens[p] instanceof NumberToken;\n }\n function isComma(p = pos) {\n return tokens[p] instanceof CommaToken;\n }\n function isOpenParen(p = pos) {\n return tokens[p] instanceof OpenParenToken;\n }\n function isCloseParen(p = pos) {\n return tokens[p] instanceof CloseParenToken;\n }\n function isFunction(p = pos) {\n return tokens[p] instanceof FunctionToken;\n }\n function isStar(p = pos) {\n return tokens[p] instanceof DelimToken && tokens[p].value === "*";\n }\n function isEOF(p = pos) {\n return tokens[p] instanceof EOFToken;\n }\n function isClauseCombinator(p = pos) {\n return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value);\n }\n function isSelectorClauseEnd(p = pos) {\n return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken;\n }\n function consumeFunctionArguments() {\n const result2 = [consumeArgument()];\n while (true) {\n skipWhitespace();\n if (!isComma())\n break;\n pos++;\n result2.push(consumeArgument());\n }\n return result2;\n }\n function consumeArgument() {\n skipWhitespace();\n if (isNumber())\n return tokens[pos++].value;\n if (isString())\n return tokens[pos++].value;\n return consumeComplexSelector();\n }\n function consumeComplexSelector() {\n const result2 = { simples: [] };\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples.push({ selector: { functions: [{ name: "scope", args: [] }] }, combinator: "" });\n } else {\n result2.simples.push({ selector: consumeSimpleSelector(), combinator: "" });\n }\n while (true) {\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples[result2.simples.length - 1].combinator = tokens[pos++].value;\n skipWhitespace();\n } else if (isSelectorClauseEnd()) {\n break;\n }\n result2.simples.push({ combinator: "", selector: consumeSimpleSelector() });\n }\n return result2;\n }\n function consumeSimpleSelector() {\n let rawCSSString = "";\n const functions = [];\n while (!isSelectorClauseEnd()) {\n if (isIdent() || isStar()) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof HashToken) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") {\n pos++;\n if (isIdent())\n rawCSSString += "." + tokens[pos++].toSource();\n else\n throw unexpected();\n } else if (tokens[pos] instanceof ColonToken) {\n pos++;\n if (isIdent()) {\n if (!customNames.has(tokens[pos].value.toLowerCase())) {\n rawCSSString += ":" + tokens[pos++].toSource();\n } else {\n const name = tokens[pos++].value.toLowerCase();\n functions.push({ name, args: [] });\n names.add(name);\n }\n } else if (isFunction()) {\n const name = tokens[pos++].value.toLowerCase();\n if (!customNames.has(name)) {\n rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`;\n } else {\n functions.push({ name, args: consumeFunctionArguments() });\n names.add(name);\n }\n skipWhitespace();\n if (!isCloseParen())\n throw unexpected();\n pos++;\n } else {\n throw unexpected();\n }\n } else if (tokens[pos] instanceof OpenSquareToken) {\n rawCSSString += "[";\n pos++;\n while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF())\n rawCSSString += tokens[pos++].toSource();\n if (!(tokens[pos] instanceof CloseSquareToken))\n throw unexpected();\n rawCSSString += "]";\n pos++;\n } else {\n throw unexpected();\n }\n }\n if (!rawCSSString && !functions.length)\n throw unexpected();\n return { css: rawCSSString || void 0, functions };\n }\n function consumeBuiltinFunctionArguments() {\n let s = "";\n let balance = 1;\n while (!isEOF()) {\n if (isOpenParen() || isFunction())\n balance++;\n if (isCloseParen())\n balance--;\n if (!balance)\n break;\n s += tokens[pos++].toSource();\n }\n return s;\n }\n const result = consumeFunctionArguments();\n if (!isEOF())\n throw unexpected();\n if (result.some((arg) => typeof arg !== "object" || !("simples" in arg)))\n throw new InvalidSelectorError(`Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n return { selector: result, names: Array.from(names) };\n}\n\n// packages/isomorphic/selectorParser.ts\nvar kNestedSelectorNames = /* @__PURE__ */ new Set(["internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near"]);\nvar kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]);\nvar customCSSNames = /* @__PURE__ */ new Set(["not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match"]);\nfunction parseSelector(selector) {\n var _a;\n const parsedStrings = parseSelectorString(selector);\n const parts = [];\n for (const part of parsedStrings.parts) {\n if (part.name === "css" || part.name === "css:light") {\n if (part.name === "css:light")\n part.body = ":light(" + part.body + ")";\n const parsedCSS = parseCSS(part.body, customCSSNames);\n parts.push({\n name: "css",\n body: parsedCSS.selector,\n source: part.body\n });\n continue;\n }\n if (kNestedSelectorNames.has(part.name)) {\n let innerSelector;\n let distance;\n try {\n const unescaped = JSON.parse("[" + part.body + "]");\n if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string")\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n innerSelector = unescaped[0];\n if (unescaped.length === 2) {\n if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name))\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n distance = unescaped[1];\n }\n } catch (e) {\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n }\n const nested = { name: part.name, source: part.body, body: { parsed: parseSelector(innerSelector), distance } };\n const lastFrame = [...nested.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame");\n const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1;\n const outerParts = ((_a = parts[0]) == null ? void 0 : _a.name) === "internal:control" && parts[0].body === "any-frame" ? parts.slice(1) : parts;\n if (lastFrameIndex !== -1 && selectorPartsEqual(nested.body.parsed.parts.slice(0, lastFrameIndex + 1), outerParts.slice(0, lastFrameIndex + 1))) {\n nested.body.parsed.parts.splice(0, lastFrameIndex + 1);\n if (nested.body.parsed.capture !== void 0) {\n if (nested.body.parsed.capture <= lastFrameIndex)\n throw new InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`);\n nested.body.parsed.capture -= lastFrameIndex + 1;\n }\n }\n parts.push(nested);\n continue;\n }\n parts.push({ ...part, source: part.body });\n }\n if (kNestedSelectorNames.has(parts[0].name))\n throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`);\n return {\n capture: parsedStrings.capture,\n parts\n };\n}\nfunction selectorPartsEqual(list1, list2) {\n return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 });\n}\nfunction stringifySelector(selector, forceEngineName) {\n if (typeof selector === "string")\n return selector;\n return selector.parts.map((p, i) => {\n let includeEngine = true;\n if (!forceEngineName && i !== selector.capture) {\n if (p.name === "css")\n includeEngine = false;\n else if (p.name === "xpath" && (p.source.startsWith("//") || p.source.startsWith("..")))\n includeEngine = false;\n }\n const prefix = includeEngine ? p.name + "=" : "";\n return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`;\n }).join(" >> ");\n}\nfunction visitAllSelectorParts(selector, visitor) {\n const visit = (selector2, nested) => {\n for (const part of selector2.parts) {\n visitor(part, nested);\n if (kNestedSelectorNames.has(part.name))\n visit(part.body.parsed, true);\n }\n };\n visit(selector, false);\n}\nfunction parseSelectorString(selector) {\n let index = 0;\n let quote;\n let start = 0;\n const result = { parts: [] };\n const append = () => {\n const part = selector.substring(start, index).trim();\n const eqIndex = part.indexOf("=");\n let name;\n let body;\n if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) {\n name = part.substring(0, eqIndex).trim();\n body = part.substring(eqIndex + 1);\n } else if (part.length > 1 && part[0] === \'"\' && part[part.length - 1] === \'"\') {\n name = "text";\n body = part;\n } else if (part.length > 1 && part[0] === "\'" && part[part.length - 1] === "\'") {\n name = "text";\n body = part;\n } else if (/^\\(*\\/\\//.test(part) || part.startsWith("..")) {\n name = "xpath";\n body = part;\n } else {\n name = "css";\n body = part;\n }\n let capture = false;\n if (name[0] === "*") {\n capture = true;\n name = name.substring(1);\n }\n result.parts.push({ name, body });\n if (capture) {\n if (result.capture !== void 0)\n throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`);\n result.capture = result.parts.length - 1;\n }\n };\n if (!selector.includes(">>")) {\n index = selector.length;\n append();\n return result;\n }\n const shouldIgnoreTextSelectorQuote = () => {\n const prefix = selector.substring(start, index);\n const match = prefix.match(/^\\s*text\\s*=(.*)$/);\n return !!match && !!match[1];\n };\n while (index < selector.length) {\n const c = selector[index];\n if (c === "\\\\" && index + 1 < selector.length) {\n index += 2;\n } else if (c === quote) {\n quote = void 0;\n index++;\n } else if (!quote && (c === \'"\' || c === "\'" || c === "`") && !shouldIgnoreTextSelectorQuote()) {\n quote = c;\n index++;\n } else if (!quote && c === ">" && selector[index + 1] === ">") {\n append();\n index += 2;\n start = index;\n } else {\n index++;\n }\n }\n append();\n return result;\n}\nfunction parseAttributeSelector(selector, allowUnquotedStrings) {\n let wp = 0;\n let EOL = selector.length === 0;\n const next = () => selector[wp] || "";\n const eat1 = () => {\n const result2 = next();\n ++wp;\n EOL = wp >= selector.length;\n return result2;\n };\n const syntaxError = (stage) => {\n if (EOL)\n throw new InvalidSelectorError(`Unexpected end of selector while parsing selector \\`${selector}\\``);\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : ""));\n };\n function skipSpaces() {\n while (!EOL && /\\s/.test(next()))\n eat1();\n }\n function isCSSNameChar(char) {\n return char >= "\\x80" || char >= "0" && char <= "9" || char >= "A" && char <= "Z" || char >= "a" && char <= "z" || char >= "0" && char <= "9" || char === "_" || char === "-";\n }\n function readIdentifier() {\n let result2 = "";\n skipSpaces();\n while (!EOL && isCSSNameChar(next()))\n result2 += eat1();\n return result2;\n }\n function readQuotedString(quote) {\n let result2 = eat1();\n if (result2 !== quote)\n syntaxError("parsing quoted string");\n while (!EOL && next() !== quote) {\n if (next() === "\\\\")\n eat1();\n result2 += eat1();\n }\n if (next() !== quote)\n syntaxError("parsing quoted string");\n result2 += eat1();\n return result2;\n }\n function readRegularExpression() {\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let source = "";\n let inClass = false;\n while (!EOL) {\n if (next() === "\\\\") {\n source += eat1();\n if (EOL)\n syntaxError("parsing regular expression");\n } else if (inClass && next() === "]") {\n inClass = false;\n } else if (!inClass && next() === "[") {\n inClass = true;\n } else if (!inClass && next() === "/") {\n break;\n }\n source += eat1();\n }\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let flags = "";\n while (!EOL && next().match(/[dgimsuvy]/))\n flags += eat1();\n try {\n return new RegExp(source, flags);\n } catch (e) {\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\`: ${e.message}`);\n }\n }\n function readAttributeToken() {\n let token = "";\n skipSpaces();\n if (next() === `\'` || next() === `"`)\n token = readQuotedString(next()).slice(1, -1);\n else\n token = readIdentifier();\n if (!token)\n syntaxError("parsing property path");\n return token;\n }\n function readOperator() {\n skipSpaces();\n let op = "";\n if (!EOL)\n op += eat1();\n if (!EOL && op !== "=")\n op += eat1();\n if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op))\n syntaxError("parsing operator");\n return op;\n }\n function readAttribute() {\n eat1();\n const jsonPath = [];\n jsonPath.push(readAttributeToken());\n skipSpaces();\n while (next() === ".") {\n eat1();\n jsonPath.push(readAttributeToken());\n skipSpaces();\n }\n if (next() === "]") {\n eat1();\n return { name: jsonPath.join("."), jsonPath, op: "", value: null, caseSensitive: false };\n }\n const operator = readOperator();\n let value = void 0;\n let caseSensitive = true;\n skipSpaces();\n if (next() === "/") {\n if (operator !== "=")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with regular expression`);\n value = readRegularExpression();\n } else if (next() === `\'` || next() === `"`) {\n value = readQuotedString(next()).slice(1, -1);\n skipSpaces();\n if (next() === "i" || next() === "I") {\n caseSensitive = false;\n eat1();\n } else if (next() === "s" || next() === "S") {\n caseSensitive = true;\n eat1();\n }\n } else {\n value = "";\n while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === "."))\n value += eat1();\n if (value === "true") {\n value = true;\n } else if (value === "false") {\n value = false;\n } else {\n if (!allowUnquotedStrings) {\n value = +value;\n if (Number.isNaN(value))\n syntaxError("parsing attribute value");\n }\n }\n }\n skipSpaces();\n if (next() !== "]")\n syntaxError("parsing attribute value");\n eat1();\n if (operator !== "=" && typeof value !== "string")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);\n return { name: jsonPath.join("."), jsonPath, op: operator, value, caseSensitive };\n }\n const result = {\n name: "",\n attributes: []\n };\n result.name = readIdentifier();\n skipSpaces();\n while (next() === "[") {\n result.attributes.push(readAttribute());\n skipSpaces();\n }\n if (!EOL)\n syntaxError(void 0);\n if (!result.name && !result.attributes.length)\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - selector cannot be empty`);\n return result;\n}\n\n// packages/isomorphic/locatorGenerators.ts\nfunction asLocator(lang, selector, isFrameLocator = false) {\n return asLocators(lang, selector, isFrameLocator, 1)[0];\n}\nfunction asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) {\n try {\n return innerAsLocators(new generators[lang](preferredQuote), parseSelector(selector), isFrameLocator, maxOutputSize);\n } catch (e) {\n return [selector];\n }\n}\nfunction innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) {\n const parts = [...parsed.parts];\n const tokens = [];\n let nextBase = isFrameLocator ? "frame-locator" : "page";\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const base = nextBase;\n nextBase = "locator";\n if (part.name === "internal:describe")\n continue;\n if (part.name === "nth") {\n if (part.body === "0")\n tokens.push([factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0")]);\n else if (part.body === "-1")\n tokens.push([factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1")]);\n else\n tokens.push([factory.generateLocator(base, "nth", part.body)]);\n continue;\n }\n if (part.name === "visible") {\n const tokenList = [];\n if (part.body === "true")\n tokenList.push(factory.generateLocator(base, "visible", ""));\n tokenList.push(factory.generateLocator(base, "filter-visible", part.body), factory.generateLocator(base, "default", `visible=${part.body}`));\n tokens.push(tokenList);\n continue;\n }\n if (part.name === "internal:text") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "text", text, { exact })]);\n continue;\n }\n if (part.name === "internal:has-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has-not-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-not-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "has", inner)));\n continue;\n }\n if (part.name === "internal:has-not") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "hasNot", inner)));\n continue;\n }\n if (part.name === "internal:and") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "and", inner)));\n continue;\n }\n if (part.name === "internal:or") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "or", inner)));\n continue;\n }\n if (part.name === "internal:chain") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "chain", inner)));\n continue;\n }\n if (part.name === "internal:label") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "label", text, { exact })]);\n continue;\n }\n if (part.name === "internal:role") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const options = { attrs: [] };\n for (const attr of attrSelector.attributes) {\n if (attr.name === "name" || attr.name === "description") {\n if (typeof attr.value === "string") {\n if (options.exact !== void 0 && options.exact !== attr.caseSensitive)\n throw new Error(`Conflicting exactness in internal:role selector: ${stringifySelector({ parts: [part] })}`);\n options.exact = attr.caseSensitive;\n }\n options[attr.name] = attr.value;\n } else {\n if (attr.name === "level" && typeof attr.value === "string")\n attr.value = +attr.value;\n options.attrs.push({ name: attr.name === "include-hidden" ? "includeHidden" : attr.name, value: attr.value });\n }\n }\n tokens.push([factory.generateLocator(base, "role", attrSelector.name, options)]);\n continue;\n }\n if (part.name === "internal:testid") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { value } = attrSelector.attributes[0];\n tokens.push([factory.generateLocator(base, "test-id", value)]);\n continue;\n }\n if (part.name === "internal:attr") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { name, value, caseSensitive } = attrSelector.attributes[0];\n const text = value;\n const exact = !!caseSensitive;\n if (name === "placeholder") {\n tokens.push([factory.generateLocator(base, "placeholder", text, { exact })]);\n continue;\n }\n if (name === "alt") {\n tokens.push([factory.generateLocator(base, "alt", text, { exact })]);\n continue;\n }\n if (name === "title") {\n tokens.push([factory.generateLocator(base, "title", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:control" && part.body === "any-frame") {\n tokens.push([factory.generateLocator(base, "any-frame", "")]);\n nextBase = "frame-locator";\n continue;\n }\n if (part.name === "internal:control" && part.body === "enter-frame") {\n const lastTokens = tokens[tokens.length - 1];\n const lastPart = parts[index - 1];\n const transformed = lastTokens.map((token) => factory.chainLocators([token, factory.generateLocator(base, "frame", "")]));\n if (["xpath", "css"].includes(lastPart.name)) {\n transformed.push(\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] })),\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] }, true))\n );\n }\n lastTokens.splice(0, lastTokens.length, ...transformed);\n nextBase = "frame-locator";\n continue;\n }\n const nextPart = parts[index + 1];\n const selectorPart = stringifySelector({ parts: [part] });\n const locatorPart = factory.generateLocator(base, "default", selectorPart);\n if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) {\n const { exact, text } = detectExact(nextPart.body);\n if (!exact) {\n const nextLocatorPart = factory.generateLocator("locator", nextPart.name === "internal:has-text" ? "has-text" : "has-not-text", text, { exact });\n const options = {};\n if (nextPart.name === "internal:has-text")\n options.hasText = text;\n else\n options.hasNotText = text;\n const combinedPart = factory.generateLocator(base, "default", selectorPart, options);\n tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]);\n index++;\n continue;\n }\n }\n let locatorPartWithEngine;\n if (["xpath", "css"].includes(part.name)) {\n const selectorPart2 = stringifySelector(\n { parts: [part] },\n /* forceEngineName */\n true\n );\n locatorPartWithEngine = factory.generateLocator(base, "default", selectorPart2);\n }\n tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean));\n }\n return combineTokens(factory, tokens, maxOutputSize);\n}\nfunction combineTokens(factory, tokens, maxOutputSize) {\n const currentTokens = tokens.map(() => "");\n const result = [];\n const visit = (index) => {\n if (index === tokens.length) {\n result.push(factory.chainLocators(currentTokens));\n return result.length < maxOutputSize;\n }\n for (const taken of tokens[index]) {\n currentTokens[index] = taken;\n if (!visit(index + 1))\n return false;\n }\n return true;\n };\n visit(0);\n return result;\n}\nfunction detectExact(text) {\n let exact = false;\n const match = text.match(/^\\/(.*)\\/([dgimsuvy]*)$/);\n if (match)\n return { text: new RegExp(match[1], match[2]) };\n if (text.endsWith(\'"\')) {\n text = JSON.parse(text);\n exact = true;\n } else if (text.endsWith(\'"s\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = true;\n } else if (text.endsWith(\'"i\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = false;\n }\n return { exact, text };\n}\nvar JavaScriptLocatorFactory = class {\n constructor(preferredQuote) {\n this.preferredQuote = preferredQuote;\n }\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "any-frame":\n return `frameLocator()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `visible()`;\n case "filter-visible":\n return `filter({ visible: ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`name: ${this.regexToSourceString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`name: ${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`description: ${this.regexToSourceString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description: ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact: true`);\n for (const { name, value } of options.attrs)\n attrs.push(`${name}: ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : "";\n return `getByRole(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter({ hasText: ${this.toHasText(body)} })`;\n case "has-not-text":\n return `filter({ hasNotText: ${this.toHasText(body)} })`;\n case "has":\n return `filter({ has: ${body} })`;\n case "hasNot":\n return `filter({ hasNot: ${body} })`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToSourceString(re) {\n return normalizeEscapedRegexQuotes(String(re));\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToSourceString(body)})`;\n return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToSourceString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToSourceString(value);\n return this.quote(value);\n }\n quote(text) {\n var _a;\n return escapeWithQuotes(text, (_a = this.preferredQuote) != null ? _a : "\'");\n }\n};\nvar PythonLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frame_locator(${this.quote(body)})`;\n case "frame":\n return `content_frame`;\n case "any-frame":\n return `frame_locator()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first`;\n case "last":\n return `last`;\n case "visible":\n return `visible`;\n case "filter-visible":\n return `filter(visible=${body === "true" ? "True" : "False"})`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`name=${this.regexToString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`name=${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`description=${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description=${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact=True`);\n for (const { name, value } of options.attrs) {\n let valueString = typeof value === "string" ? this.quote(value) : value;\n if (typeof value === "boolean")\n valueString = value ? "True" : "False";\n attrs.push(`${toSnakeCase(name)}=${valueString}`);\n }\n const attrString = attrs.length ? `, ${attrs.join(", ")}` : "";\n return `get_by_role(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter(has_text=${this.toHasText(body)})`;\n case "has-not-text":\n return `filter(has_not_text=${this.toHasText(body)})`;\n case "has":\n return `filter(has=${body})`;\n case "hasNot":\n return `filter(has_not=${body})`;\n case "and":\n return `and_(${body})`;\n case "or":\n return `or_(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `get_by_test_id(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("get_by_text", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("get_by_alt_text", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("get_by_placeholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("get_by_label", body, !!options.exact);\n case "title":\n return this.toCallWithExact("get_by_title", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = regexFlagsSuffix(body, "re", regexFlagNames.python);\n return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\\\\//, "/").replace(/"/g, \'\\\\"\')}"${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, exact=True)`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return `${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JavaLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n let clazz;\n switch (base) {\n case "page":\n clazz = "Page";\n break;\n case "frame-locator":\n clazz = "FrameLocator";\n break;\n case "locator":\n clazz = "Locator";\n break;\n }\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "any-frame":\n return `frameLocator()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `visible()`;\n case "filter-visible":\n return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`.setName(${this.regexToString(options.name)})`);\n else if (typeof options.name === "string")\n attrs.push(`.setName(${this.quote(options.name)})`);\n if (isRegExp(options.description))\n attrs.push(`.setDescription(${this.regexToString(options.description)})`);\n else if (typeof options.description === "string")\n attrs.push(`.setDescription(${this.quote(options.description)})`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`.setExact(true)`);\n for (const { name, value } of options.attrs)\n attrs.push(`.set${toTitleCase(name)}(${typeof value === "string" ? this.quote(value) : value})`);\n const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : "";\n return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`;\n case "has-text":\n return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`;\n case "has-not-text":\n return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`;\n case "has":\n return `filter(new ${clazz}.FilterOptions().setHas(${body}))`;\n case "hasNot":\n return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact(clazz, "getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact(clazz, "getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact(clazz, "getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact(clazz, "getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = regexFlagsSuffix(body, "Pattern", regexFlagNames.java);\n return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(clazz, method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar CSharpLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`;\n return `Locator(${this.quote(body)})`;\n case "frame-locator":\n return `FrameLocator(${this.quote(body)})`;\n case "frame":\n return `ContentFrame`;\n case "any-frame":\n return `FrameLocator()`;\n case "nth":\n return `Nth(${body})`;\n case "first":\n return `First`;\n case "last":\n return `Last`;\n case "visible":\n return `Visible`;\n case "filter-visible":\n return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`NameRegex = ${this.regexToString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`Name = ${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`DescriptionRegex = ${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`Description = ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`Exact = true`);\n for (const { name, value } of options.attrs)\n attrs.push(`${toTitleCase(name)} = ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : "";\n return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`;\n case "has-text":\n return `Filter(new() { ${this.toHasText(body)} })`;\n case "has-not-text":\n return `Filter(new() { ${this.toHasNotText(body)} })`;\n case "has":\n return `Filter(new() { Has = ${body} })`;\n case "hasNot":\n return `Filter(new() { HasNot = ${body} })`;\n case "and":\n return `And(${body})`;\n case "or":\n return `Or(${body})`;\n case "chain":\n return `Locator(${body})`;\n case "test-id":\n return `GetByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("GetByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("GetByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("GetByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("GetByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("GetByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = regexFlagsSuffix(body, "RegexOptions", regexFlagNames.csharp);\n return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new() { Exact = true })`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return `HasTextRegex = ${this.regexToString(body)}`;\n return `HasText = ${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n toHasNotText(body) {\n if (isRegExp(body))\n return `HasNotTextRegex = ${this.regexToString(body)}`;\n return `HasNotText = ${this.quote(body)}`;\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JsonlLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n return JSON.stringify({\n kind,\n body,\n options\n });\n }\n chainLocators(locators) {\n const objects = locators.map((l) => JSON.parse(l));\n for (let i = 0; i < objects.length - 1; ++i) {\n let tail = objects[i];\n while (tail.next)\n tail = tail.next;\n tail.next = objects[i + 1];\n }\n return JSON.stringify(objects[0]);\n }\n};\nvar generators = {\n javascript: JavaScriptLocatorFactory,\n python: PythonLocatorFactory,\n java: JavaLocatorFactory,\n csharp: CSharpLocatorFactory,\n jsonl: JsonlLocatorFactory\n};\nvar regexFlagNames = {\n python: { i: "IGNORECASE", m: "MULTILINE", s: "DOTALL" },\n java: { i: "CASE_INSENSITIVE", m: "MULTILINE", s: "DOTALL" },\n csharp: { i: "IgnoreCase", m: "Multiline", s: "Singleline" }\n};\nfunction regexFlagsSuffix(body, flagsEnum, names) {\n const flags = [...body.flags].filter((flag) => flag in names).map((flag) => `${flagsEnum}.${names[flag]}`);\n return flags.length ? `, ${flags.join(" | ")}` : "";\n}\nfunction isRegExp(obj) {\n return obj instanceof RegExp;\n}\n\n// packages/isomorphic/locatorUtils.ts\nfunction getByAttributeTextSelector(attrName, text, options) {\n return `internal:attr=[${attrName}=${escapeForAttributeSelector(text, (options == null ? void 0 : options.exact) || false)}]`;\n}\nfunction splitTestIdAttributeNames(testIdAttributeName) {\n return testIdAttributeName.split(",");\n}\nfunction encodeTestIdAttributeName(testIdAttributeName) {\n return testIdAttributeName.includes(",") ? JSON.stringify(testIdAttributeName) : testIdAttributeName;\n}\nfunction getByTestIdSelector(testIdAttributeName, testId) {\n return `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName)}=${escapeForAttributeSelector(testId, true)}]`;\n}\nfunction getByLabelSelector(text, options) {\n return "internal:label=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByAltTextSelector(text, options) {\n return getByAttributeTextSelector("alt", text, options);\n}\nfunction getByTitleSelector(text, options) {\n return getByAttributeTextSelector("title", text, options);\n}\nfunction getByPlaceholderSelector(text, options) {\n return getByAttributeTextSelector("placeholder", text, options);\n}\nfunction getByTextSelector(text, options) {\n return "internal:text=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByRoleSelector(role, options = {}) {\n const props = [];\n if (options.checked !== void 0)\n props.push(["checked", String(options.checked)]);\n if (options.disabled !== void 0)\n props.push(["disabled", String(options.disabled)]);\n if (options.selected !== void 0)\n props.push(["selected", String(options.selected)]);\n if (options.expanded !== void 0)\n props.push(["expanded", String(options.expanded)]);\n if (options.includeHidden !== void 0)\n props.push(["include-hidden", String(options.includeHidden)]);\n if (options.level !== void 0)\n props.push(["level", String(options.level)]);\n if (options.name !== void 0)\n props.push(["name", escapeForAttributeSelector(options.name, !!options.exact)]);\n if (options.description !== void 0)\n props.push(["description", escapeForAttributeSelector(options.description, !!options.exact)]);\n if (options.pressed !== void 0)\n props.push(["pressed", String(options.pressed)]);\n return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`;\n}\n\n// packages/injected/src/ariaSnapshotDistiller.ts\nfunction distillAriaSnapshot(snapshot, options) {\n runPlugins(snapshot, options.mode === "ai" ? aiPlugins : normalizePlugins, options);\n}\nfunction runPlugins(snapshot, plugins, options) {\n var _a, _b;\n const ctx = { snapshot, depth: -1, maxDepth: options.depth, ancestors: [], pendingContentRefs: /* @__PURE__ */ new Set() };\n const traverse = (node, depth) => {\n const children = [];\n const visitChild = (child) => {\n var _a2, _b2;\n if (typeof child === "string") {\n children.push(child);\n return;\n }\n ctx.depth = depth + 1;\n for (const plugin of plugins) {\n const result = (_a2 = plugin.enter) == null ? void 0 : _a2.call(plugin, child, ctx);\n if (result === "remove")\n return;\n if (result === "unwrap") {\n child.children.forEach(visitChild);\n return;\n }\n }\n traverse(child, depth + 1);\n ctx.depth = depth + 1;\n for (const plugin of plugins) {\n const result = (_b2 = plugin.exit) == null ? void 0 : _b2.call(plugin, child, ctx);\n if (result === "remove")\n return;\n if (result === "unwrap") {\n children.push(...child.children);\n return;\n }\n }\n children.push(child);\n };\n ctx.ancestors.push(node);\n node.children.forEach(visitChild);\n ctx.ancestors.pop();\n node.children = children;\n };\n for (const plugin of plugins)\n (_a = plugin.enter) == null ? void 0 : _a.call(plugin, snapshot.root, ctx);\n traverse(snapshot.root, -1);\n ctx.depth = -1;\n for (const plugin of plugins)\n (_b = plugin.exit) == null ? void 0 : _b.call(plugin, snapshot.root, ctx);\n}\nfunction isLeafGeneric(node) {\n return node.role === "generic" && node.children.every((child) => typeof child === "string");\n}\nfunction isClickTargetRoot(node, ctx) {\n return !!node.ref && hasPointerCursor(node) && !ctx.ancestors.some((ancestor) => !!ancestor.ref && hasPointerCursor(ancestor));\n}\nvar mergeStringChildren = {\n name: "mergeStringChildren",\n exit(node) {\n const children = [];\n const buffer = [];\n const flush = () => {\n if (!buffer.length)\n return;\n const text = normalizeWhiteSpace(buffer.join(""));\n if (text)\n children.push(text);\n buffer.length = 0;\n };\n for (const child of node.children) {\n if (typeof child === "string") {\n buffer.push(child);\n } else {\n flush();\n children.push(child);\n }\n }\n flush();\n node.children = children;\n if (node.children.length === 1 && node.children[0] === node.name)\n node.children = [];\n }\n};\nvar unwrapSingleChildGenerics = {\n name: "unwrapSingleChildGenerics",\n exit(node, ctx) {\n if (node.role !== "generic" || node.name || node.children.length > 1 || !node.children.every((child) => typeof child !== "string" && !!child.ref))\n return;\n if (!node.children.length && isClickTargetRoot(node, ctx))\n return;\n return "unwrap";\n }\n};\nvar removeNamelessImages = {\n name: "removeNamelessImages",\n exit(node, ctx) {\n if (node.role === "img" && !node.name && !node.children.length && !isClickTargetRoot(node, ctx))\n return "remove";\n }\n};\nvar removeRedundantNames = {\n name: "removeRedundantNames",\n enter(node, ctx) {\n var _a;\n if (!node.ref)\n return;\n for (const ref of ((_a = ctx.snapshot.info.get(node.ref)) == null ? void 0 : _a.nameFromContentRefs) || [])\n ctx.pendingContentRefs.add(ref);\n const beyondDepth = !!ctx.maxDepth && ctx.depth > ctx.maxDepth;\n if (!beyondDepth && !isLeafGeneric(node))\n ctx.pendingContentRefs.delete(node.ref);\n },\n exit(node, ctx) {\n var _a;\n if (!node.ref)\n return;\n const nameFromContentRefs = (_a = ctx.snapshot.info.get(node.ref)) == null ? void 0 : _a.nameFromContentRefs;\n if (!(nameFromContentRefs == null ? void 0 : nameFromContentRefs.length))\n return;\n if (nameFromContentRefs.every((ref) => !ctx.pendingContentRefs.has(ref))) {\n node.name = "";\n } else {\n for (const ref of nameFromContentRefs)\n ctx.pendingContentRefs.delete(ref);\n }\n }\n};\nvar removeNameRepeatingChild = {\n name: "removeNameRepeatingChild",\n exit(node, ctx) {\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n if (!(parent == null ? void 0 : parent.name) || node.role !== "generic" || node.active || Object.keys(node.props).length)\n return;\n const singleTextChild = node.children.length === 1 && typeof node.children[0] === "string" ? node.children[0] : void 0;\n const text = node.name ? node.children.length ? void 0 : node.name : singleTextChild;\n if (text && text === parent.name) {\n if (node.ref)\n ctx.pendingContentRefs.add(node.ref);\n return "remove";\n }\n }\n};\nvar inlineTextIntoGeneric = {\n name: "inlineTextIntoGeneric",\n exit(node) {\n if (node.role !== "generic" || Object.keys(node.props).length || node.children.length !== 1)\n return;\n const child = node.children[0];\n if (typeof child === "string")\n return;\n if (child.role !== "generic" || child.name || child.active || Object.keys(child.props).length)\n return;\n if (child.children.length === 1 && typeof child.children[0] === "string")\n node.children = [child.children[0]];\n }\n};\nvar normalizePlugins = [\n mergeStringChildren,\n unwrapSingleChildGenerics\n];\nvar aiPlugins = [\n mergeStringChildren,\n removeNamelessImages,\n removeRedundantNames,\n inlineTextIntoGeneric,\n removeNameRepeatingChild,\n unwrapSingleChildGenerics\n];\n\n// packages/injected/src/domUtils.ts\nvar globalOptions = {};\nfunction setGlobalOptions(options) {\n globalOptions = options;\n}\nfunction isInsideScope(scope, element) {\n while (element) {\n if (scope.contains(element))\n return true;\n element = enclosingShadowHost(element);\n }\n return false;\n}\nfunction parentElementOrShadowHost(element) {\n if (element.parentElement)\n return element.parentElement;\n if (!element.parentNode)\n return;\n if (element.parentNode.nodeType === 11 && element.parentNode.host)\n return element.parentNode.host;\n}\nfunction enclosingShadowRootOrDocument(element) {\n let node = element;\n while (node.parentNode)\n node = node.parentNode;\n if (node.nodeType === 11 || node.nodeType === 9)\n return node;\n}\nfunction enclosingShadowHost(element) {\n while (element.parentElement)\n element = element.parentElement;\n return parentElementOrShadowHost(element);\n}\nfunction closestCrossShadow(element, css, scope) {\n while (element) {\n const closest = element.closest(css);\n if (scope && closest !== scope && (closest == null ? void 0 : closest.contains(scope)))\n return;\n if (closest)\n return closest;\n element = enclosingShadowHost(element);\n }\n}\nfunction getElementComputedStyle(element, pseudo) {\n const cache = pseudo === "::before" ? cacheStyleBefore : pseudo === "::after" ? cacheStyleAfter : cacheStyle;\n if (cache && cache.has(element))\n return cache.get(element);\n const style = element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : void 0;\n cache == null ? void 0 : cache.set(element, style);\n return style;\n}\nfunction isElementStyleVisibilityVisible(element, style) {\n const cached = cacheStyleVisibility == null ? void 0 : cacheStyleVisibility.get(element);\n if (cached !== void 0)\n return cached;\n const result = computeElementStyleVisibilityVisible(element, style);\n cacheStyleVisibility == null ? void 0 : cacheStyleVisibility.set(element, result);\n return result;\n}\nfunction computeElementStyleVisibilityVisible(element, style) {\n style = style != null ? style : getElementComputedStyle(element);\n if (!style)\n return true;\n if (!element.checkVisibility() && !isWebKitListBoxOptionVisible(element, style))\n return false;\n if (style.visibility !== "visible")\n return false;\n return true;\n}\nfunction isListBoxSelect(select) {\n return select.multiple || select.size > 1;\n}\nfunction isWebKitListBoxOptionVisible(element, style) {\n var _a;\n if (globalOptions.browserNameForWorkarounds !== "webkit" || element.nodeName !== "OPTION" || style.display === "none")\n return false;\n const select = element.closest("select");\n if (!select || !isListBoxSelect(select))\n return false;\n for (let e = element.parentElement; e && e !== select; e = e.parentElement) {\n if (((_a = getElementComputedStyle(e)) == null ? void 0 : _a.display) === "none")\n return false;\n }\n return isElementStyleVisibilityVisible(select);\n}\nfunction computeBox(element) {\n const style = getElementComputedStyle(element);\n if (!style)\n return { visible: true, inline: false };\n const cursor = style.cursor;\n if (style.display === "contents") {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && isElementVisible(child))\n return { visible: true, inline: false, cursor };\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return { visible: true, inline: true, cursor };\n }\n return { visible: false, inline: false, cursor };\n }\n if (!isElementStyleVisibilityVisible(element, style))\n return { cursor, visible: false, inline: false };\n const rect = element.getBoundingClientRect();\n return { cursor, visible: rect.width > 0 && rect.height > 0, inline: style.display === "inline" };\n}\nfunction isElementVisible(element) {\n return computeBox(element).visible;\n}\nvar kTextNodeRange = /* @__PURE__ */ Symbol("playwrightTextNodeRange");\nfunction isVisibleTextNode(node) {\n var _a;\n const document = node.ownerDocument;\n const range = (_a = document[kTextNodeRange]) != null ? _a : document[kTextNodeRange] = document.createRange();\n range.selectNode(node);\n const rect = range.getBoundingClientRect();\n const result = rect.width > 0 && rect.height > 0;\n range.setStart(document, 0);\n range.collapse(true);\n return result;\n}\nfunction elementSafeTagName(element) {\n const tagName = element.tagName;\n if (typeof tagName === "string") {\n const firstCharCode = tagName.charCodeAt(0);\n if (firstCharCode >= 97 && firstCharCode <= 122)\n return tagName.toUpperCase();\n return tagName;\n }\n if (element instanceof HTMLFormElement)\n return "FORM";\n return element.tagName.toUpperCase();\n}\nvar cacheStyle;\nvar cacheStyleBefore;\nvar cacheStyleAfter;\nvar cacheStyleVisibility;\nvar cachesCounter = 0;\nfunction beginDOMCaches() {\n ++cachesCounter;\n cacheStyle != null ? cacheStyle : cacheStyle = /* @__PURE__ */ new Map();\n cacheStyleBefore != null ? cacheStyleBefore : cacheStyleBefore = /* @__PURE__ */ new Map();\n cacheStyleAfter != null ? cacheStyleAfter : cacheStyleAfter = /* @__PURE__ */ new Map();\n cacheStyleVisibility != null ? cacheStyleVisibility : cacheStyleVisibility = /* @__PURE__ */ new Map();\n}\nfunction endDOMCaches() {\n if (!--cachesCounter) {\n cacheStyle = void 0;\n cacheStyleBefore = void 0;\n cacheStyleAfter = void 0;\n cacheStyleVisibility = void 0;\n }\n}\n\n// packages/injected/src/roleUtils.ts\nfunction hasExplicitAccessibleName(e) {\n return e.hasAttribute("aria-label") || e.hasAttribute("aria-labelledby");\n}\nvar kAncestorPreventingLandmark = "article:not([role]), aside:not([role]), main:not([role]), nav:not([role]), section:not([role]), [role=article], [role=complementary], [role=main], [role=navigation], [role=region]";\nvar kGlobalAriaAttributes = [\n ["aria-atomic", void 0],\n ["aria-busy", void 0],\n ["aria-controls", void 0],\n ["aria-current", void 0],\n ["aria-describedby", void 0],\n ["aria-details", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-disabled\', undefined],\n ["aria-dropeffect", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-errormessage\', undefined],\n ["aria-flowto", void 0],\n ["aria-grabbed", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-haspopup\', undefined],\n ["aria-hidden", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-invalid\', undefined],\n ["aria-keyshortcuts", void 0],\n ["aria-label", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-labelledby", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-live", void 0],\n ["aria-owns", void 0],\n ["aria-relevant", void 0],\n ["aria-roledescription", ["generic"]]\n];\nfunction hasGlobalAriaAttribute(element, forRole) {\n return kGlobalAriaAttributes.some(([attr, prohibited]) => {\n return !(prohibited == null ? void 0 : prohibited.includes(forRole || "")) && element.hasAttribute(attr);\n });\n}\nfunction hasTabIndex(element) {\n return !Number.isNaN(Number(String(element.getAttribute("tabindex"))));\n}\nfunction isFocusable(element) {\n return !isNativelyDisabled(element) && (isNativelyFocusable(element) || hasTabIndex(element));\n}\nfunction isNativelyFocusable(element) {\n const tagName = elementSafeTagName(element);\n if (["BUTTON", "DETAILS", "SELECT", "TEXTAREA"].includes(tagName))\n return true;\n if (tagName === "A" || tagName === "AREA")\n return element.hasAttribute("href");\n if (tagName === "INPUT")\n return !element.hidden;\n return false;\n}\nvar kImplicitRoleByTagName = {\n "A": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "AREA": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "ARTICLE": () => "article",\n "ASIDE": () => "complementary",\n "BLOCKQUOTE": () => "blockquote",\n "BUTTON": () => "button",\n "CAPTION": () => "caption",\n "CODE": () => "code",\n "DATALIST": () => "listbox",\n "DD": () => "definition",\n "DEL": () => "deletion",\n "DETAILS": () => "group",\n "DFN": () => "term",\n "DIALOG": () => "dialog",\n "DT": () => "term",\n "EM": () => "emphasis",\n "FIELDSET": () => "group",\n "FIGURE": () => "figure",\n "FOOTER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "contentinfo",\n "FORM": (e) => hasExplicitAccessibleName(e) ? "form" : null,\n "H1": () => "heading",\n "H2": () => "heading",\n "H3": () => "heading",\n "H4": () => "heading",\n "H5": () => "heading",\n "H6": () => "heading",\n "HEADER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "banner",\n "HR": () => "separator",\n "HTML": () => "document",\n "IMG": (e) => e.getAttribute("alt") === "" && !e.getAttribute("title") && !hasGlobalAriaAttribute(e) && !hasTabIndex(e) ? "presentation" : "img",\n "INPUT": (e) => {\n const type = e.type.toLowerCase();\n if (["email", "search", "tel", "text", "url", ""].includes(type)) {\n const list = getIdRefs(e, e.getAttribute("list"))[0];\n if (list && elementSafeTagName(list) === "DATALIST")\n return "combobox";\n return type === "search" ? "searchbox" : "textbox";\n }\n if (type === "hidden")\n return null;\n if (type === "file")\n return "button";\n return inputTypeToRole[type] || "textbox";\n },\n "INS": () => "insertion",\n "LI": () => "listitem",\n "MAIN": () => "main",\n "MARK": () => "mark",\n "MATH": () => "math",\n "MENU": () => "list",\n "METER": () => "meter",\n "NAV": () => "navigation",\n "OL": () => "list",\n "OPTGROUP": () => "group",\n "OPTION": () => "option",\n "OUTPUT": () => "status",\n "P": () => "paragraph",\n "PROGRESS": () => "progressbar",\n "SEARCH": () => "search",\n "SECTION": (e) => hasExplicitAccessibleName(e) ? "region" : null,\n "SELECT": (e) => isListBoxSelect(e) ? "listbox" : "combobox",\n "STRONG": () => "strong",\n "SUB": () => "subscript",\n "SUP": () => "superscript",\n // For we default to Chrome behavior:\n // - Chrome reports \'img\'.\n // - Firefox reports \'diagram\' that is not in official ARIA spec yet.\n // - Safari reports \'no role\', but still computes accessible name.\n "SVG": () => "img",\n "TABLE": () => "table",\n "TBODY": () => "rowgroup",\n "TD": (e) => {\n const table = closestCrossShadow(e, "table");\n const role = table ? getExplicitAriaRole(table) : "";\n return role === "grid" || role === "treegrid" ? "gridcell" : "cell";\n },\n "TEXTAREA": () => "textbox",\n "TFOOT": () => "rowgroup",\n "TH": (e) => {\n const scope = e.getAttribute("scope");\n if (scope === "col" || scope === "colgroup")\n return "columnheader";\n if (scope === "row" || scope === "rowgroup")\n return "rowheader";\n const nextSibling = e.nextElementSibling;\n const prevSibling = e.previousElementSibling;\n const row = !!e.parentElement && elementSafeTagName(e.parentElement) === "TR" ? e.parentElement : void 0;\n if (!nextSibling && !prevSibling) {\n if (row) {\n const table = closestCrossShadow(row, "table");\n if (table && table.rows.length <= 1)\n return null;\n }\n return "columnheader";\n }\n if (isHeaderCell(nextSibling) && isHeaderCell(prevSibling))\n return "columnheader";\n if (isNonEmptyDataCell(nextSibling) || isNonEmptyDataCell(prevSibling))\n return "rowheader";\n return "columnheader";\n },\n "THEAD": () => "rowgroup",\n "TIME": () => "time",\n "TR": () => "row",\n "UL": () => "list"\n};\nfunction isHeaderCell(element) {\n return !!element && elementSafeTagName(element) === "TH";\n}\nfunction isNonEmptyDataCell(element) {\n var _a;\n if (!element || elementSafeTagName(element) !== "TD")\n return false;\n return !!(((_a = element.textContent) == null ? void 0 : _a.trim()) || element.children.length > 0);\n}\nvar kPresentationInheritanceParents = {\n "DD": ["DL", "DIV"],\n "DIV": ["DL"],\n "DT": ["DL", "DIV"],\n "LI": ["OL", "UL"],\n "TBODY": ["TABLE"],\n "TD": ["TR"],\n "TFOOT": ["TABLE"],\n "TH": ["TR"],\n "THEAD": ["TABLE"],\n "TR": ["THEAD", "TBODY", "TFOOT", "TABLE"]\n};\nfunction getImplicitAriaRole(element) {\n var _a;\n const implicitRole = ((_a = kImplicitRoleByTagName[elementSafeTagName(element)]) == null ? void 0 : _a.call(kImplicitRoleByTagName, element)) || "";\n if (!implicitRole)\n return null;\n let ancestor = element;\n while (ancestor) {\n const parent = parentElementOrShadowHost(ancestor);\n const parents = kPresentationInheritanceParents[elementSafeTagName(ancestor)];\n if (!parents || !parent || !parents.includes(elementSafeTagName(parent)))\n break;\n const parentExplicitRole = getExplicitAriaRole(parent);\n if ((parentExplicitRole === "none" || parentExplicitRole === "presentation") && !hasPresentationConflictResolution(parent, parentExplicitRole))\n return parentExplicitRole;\n ancestor = parent;\n }\n return implicitRole;\n}\nvar validRoles = [\n "alert",\n "alertdialog",\n "application",\n "article",\n "banner",\n "blockquote",\n "button",\n "caption",\n "cell",\n "checkbox",\n "code",\n "columnheader",\n "combobox",\n "complementary",\n "contentinfo",\n "definition",\n "deletion",\n "dialog",\n "directory",\n "document",\n "emphasis",\n "feed",\n "figure",\n "form",\n "generic",\n "grid",\n "gridcell",\n "group",\n "heading",\n "img",\n "insertion",\n "link",\n "list",\n "listbox",\n "listitem",\n "log",\n "main",\n "mark",\n "marquee",\n "math",\n "meter",\n "menu",\n "menubar",\n "menuitem",\n "menuitemcheckbox",\n "menuitemradio",\n "navigation",\n "none",\n "note",\n "option",\n "paragraph",\n "presentation",\n "progressbar",\n "radio",\n "radiogroup",\n "region",\n "row",\n "rowgroup",\n "rowheader",\n "scrollbar",\n "search",\n "searchbox",\n "separator",\n "slider",\n "spinbutton",\n "status",\n "strong",\n "subscript",\n "superscript",\n "switch",\n "tab",\n "table",\n "tablist",\n "tabpanel",\n "term",\n "textbox",\n "time",\n "timer",\n "toolbar",\n "tooltip",\n "tree",\n "treegrid",\n "treeitem"\n];\nfunction getExplicitAriaRole(element) {\n const roles = (element.getAttribute("role") || "").split(" ").map((role) => role.trim());\n return roles.find((role) => validRoles.includes(role)) || null;\n}\nfunction hasPresentationConflictResolution(element, role) {\n return hasGlobalAriaAttribute(element, role) || isFocusable(element);\n}\nfunction getAriaRole(element) {\n const cached = cacheAriaRole == null ? void 0 : cacheAriaRole.get(element);\n if (cached !== void 0)\n return cached;\n const role = computeAriaRole(element);\n cacheAriaRole == null ? void 0 : cacheAriaRole.set(element, role);\n return role;\n}\nfunction computeAriaRole(element) {\n const explicitRole = getExplicitAriaRole(element);\n if (!explicitRole)\n return getImplicitAriaRole(element);\n if (explicitRole === "none" || explicitRole === "presentation") {\n const implicitRole = getImplicitAriaRole(element);\n if (hasPresentationConflictResolution(element, implicitRole))\n return implicitRole;\n }\n return explicitRole;\n}\nfunction getAriaBoolean(attr) {\n return attr === null ? void 0 : attr.toLowerCase() === "true";\n}\nfunction isElementIgnoredForAria(element) {\n return ["STYLE", "SCRIPT", "NOSCRIPT", "TEMPLATE"].includes(elementSafeTagName(element));\n}\nfunction isElementHiddenForAria(element) {\n if (isElementIgnoredForAria(element))\n return true;\n const style = getElementComputedStyle(element);\n const isSlot = element.nodeName === "SLOT";\n if ((style == null ? void 0 : style.display) === "contents" && !isSlot) {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && !isElementHiddenForAria(child))\n return false;\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return false;\n }\n return true;\n }\n const isOptionInsideSelect = element.nodeName === "OPTION" && !!element.closest("select");\n if (!isOptionInsideSelect && !isSlot && !isElementStyleVisibilityVisible(element, style))\n return true;\n return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element);\n}\nfunction belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element) {\n let hidden = cacheIsHidden == null ? void 0 : cacheIsHidden.get(element);\n if (hidden === void 0) {\n hidden = false;\n if (element.parentElement && element.parentElement.shadowRoot && !element.assignedSlot)\n hidden = true;\n if (!hidden) {\n const style = getElementComputedStyle(element);\n hidden = !style || style.display === "none" || getAriaBoolean(element.getAttribute("aria-hidden")) === true;\n }\n if (!hidden) {\n const parent = parentElementOrShadowHost(element);\n if (parent)\n hidden = belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent);\n }\n cacheIsHidden == null ? void 0 : cacheIsHidden.set(element, hidden);\n }\n return hidden;\n}\nfunction getIdRefs(element, ref) {\n if (!ref)\n return [];\n const root = enclosingShadowRootOrDocument(element);\n if (!root)\n return [];\n try {\n const ids = ref.split(" ").filter((id) => !!id);\n const result = [];\n for (const id of ids) {\n const firstElement = root.querySelector("#" + CSS.escape(id));\n if (firstElement && !result.includes(firstElement))\n result.push(firstElement);\n }\n return result;\n } catch (e) {\n return [];\n }\n}\nfunction trimFlatString(s) {\n return s.trim();\n}\nfunction asFlatString(s) {\n return s.split("\\xA0").map((chunk) => chunk.replace(/\\r\\n/g, "\\n").replace(/[\\u200b\\u00ad]/g, "").replace(/\\s\\s*/g, " ")).join("\\xA0").trim();\n}\nfunction queryInAriaOwned(element, selector) {\n const result = [...element.querySelectorAll(selector)];\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns"))) {\n if (owned.matches(selector))\n result.push(owned);\n result.push(...owned.querySelectorAll(selector));\n }\n return result;\n}\nfunction getCSSContent(element, pseudo) {\n const cache = pseudo === "::before" ? cachePseudoContentBefore : pseudo === "::after" ? cachePseudoContentAfter : cachePseudoContent;\n if (cache == null ? void 0 : cache.has(element))\n return cache == null ? void 0 : cache.get(element);\n const style = getElementComputedStyle(element, pseudo);\n let content;\n if (style) {\n const contentValue = style.content;\n if (contentValue && contentValue !== "none" && contentValue !== "normal") {\n if (style.display !== "none" && style.visibility !== "hidden") {\n content = parseCSSContentPropertyAsString(element, contentValue, !!pseudo);\n }\n }\n }\n if (pseudo && content !== void 0) {\n const display = (style == null ? void 0 : style.display) || "inline";\n if (display !== "inline")\n content = " " + content + " ";\n }\n if (cache)\n cache.set(element, content);\n return content;\n}\nfunction parseCSSContentPropertyAsString(element, content, isPseudo) {\n if (!content || content === "none" || content === "normal") {\n return;\n }\n try {\n let tokens = tokenize(content).filter((token) => !(token instanceof WhitespaceToken));\n const delimIndex = tokens.findIndex((token) => token instanceof DelimToken && token.value === "/");\n if (delimIndex !== -1) {\n tokens = tokens.slice(delimIndex + 1);\n } else if (!isPseudo) {\n return;\n }\n const accumulated = [];\n let index = 0;\n while (index < tokens.length) {\n if (tokens[index] instanceof StringToken) {\n accumulated.push(tokens[index].value);\n index++;\n } else if (index + 2 < tokens.length && tokens[index] instanceof FunctionToken && tokens[index].value === "attr" && tokens[index + 1] instanceof IdentToken && tokens[index + 2] instanceof CloseParenToken) {\n const attrName = tokens[index + 1].value;\n accumulated.push(element.getAttribute(attrName) || "");\n index += 3;\n } else {\n return;\n }\n }\n return accumulated.join("");\n } catch {\n }\n}\nfunction getAriaLabelledByElements(element) {\n const ref = element.getAttribute("aria-labelledby");\n if (ref === null)\n return null;\n const refs = getIdRefs(element, ref);\n return refs.length ? refs : null;\n}\nfunction allowsNameFromContent(role, targetDescendant) {\n const alwaysAllowsNameFromContent = ["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch", "tab", "tooltip", "treeitem"].includes(role);\n const descendantAllowsNameFromContent = targetDescendant && ["", "caption", "code", "contentinfo", "definition", "deletion", "emphasis", "insertion", "list", "listitem", "mark", "none", "paragraph", "presentation", "region", "row", "rowgroup", "section", "strong", "subscript", "superscript", "table", "term", "time"].includes(role);\n return alwaysAllowsNameFromContent || descendantAllowsNameFromContent;\n}\nfunction computeAccessibleNameComposite(element, includeHidden, collectElements) {\n const elementProhibitsNaming = ["caption", "code", "definition", "deletion", "emphasis", "generic", "insertion", "mark", "paragraph", "presentation", "strong", "subscript", "suggestion", "superscript", "term", "time"].includes(getAriaRole(element) || "");\n if (elementProhibitsNaming)\n return { ...emptyCompositeString(), derivedFromContent: false };\n const outDerivedFromContent = { value: false };\n const result = getTextAlternativeInternal(element, {\n includeHidden,\n collectElements,\n outDerivedFromContent,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInTargetElement: "self"\n });\n return { text: asFlatString(result.text), elements: result.elements, derivedFromContent: outDerivedFromContent.value };\n}\nfunction getElementAccessibleName(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleNameHidden : cacheAccessibleName;\n let accessibleName = cache == null ? void 0 : cache.get(element);\n if (accessibleName === void 0) {\n accessibleName = computeAccessibleNameComposite(\n element,\n includeHidden,\n true\n /* collectElements */\n );\n cache == null ? void 0 : cache.set(element, accessibleName);\n }\n return accessibleName;\n}\nfunction getElementAccessibleNameText(element, includeHidden) {\n var _a;\n const composite = (_a = includeHidden ? cacheAccessibleNameHidden : cacheAccessibleName) == null ? void 0 : _a.get(element);\n if (composite !== void 0)\n return composite.text;\n const cache = includeHidden ? cacheAccessibleNameTextHidden : cacheAccessibleNameText;\n let text = cache == null ? void 0 : cache.get(element);\n if (text === void 0) {\n text = computeAccessibleNameComposite(\n element,\n includeHidden,\n false\n /* collectElements */\n ).text;\n cache == null ? void 0 : cache.set(element, text);\n }\n return text;\n}\nfunction getElementAccessibleDescription(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleDescriptionHidden : cacheAccessibleDescription;\n let accessibleDescription = cache == null ? void 0 : cache.get(element);\n if (accessibleDescription === void 0) {\n accessibleDescription = { text: "", derivedFromContent: false };\n if (element.hasAttribute("aria-describedby")) {\n const describedBy = getIdRefs(element, element.getAttribute("aria-describedby"));\n accessibleDescription.text = asFlatString(describedBy.map((ref) => getTextAlternativeInternal(ref, {\n includeHidden,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: ref, hidden: isElementHiddenForAria(ref) }\n }).text).join(" "));\n accessibleDescription.derivedFromContent = describedBy.some((ref) => ref === element || element.contains(ref));\n } else if (element.hasAttribute("aria-description")) {\n accessibleDescription.text = asFlatString(element.getAttribute("aria-description") || "");\n } else {\n accessibleDescription.text = asFlatString(element.getAttribute("title") || "");\n }\n cache == null ? void 0 : cache.set(element, accessibleDescription);\n }\n return accessibleDescription;\n}\nvar kAriaInvalidRoles = [\n "application",\n "checkbox",\n "columnheader",\n "combobox",\n "gridcell",\n "listbox",\n "radiogroup",\n "rowheader",\n "searchbox",\n "slider",\n "spinbutton",\n "switch",\n "textbox",\n "tree"\n];\nfunction getAriaInvalid(element) {\n const ariaInvalid = element.getAttribute("aria-invalid");\n if (!ariaInvalid || ariaInvalid.trim() === "" || ariaInvalid.toLocaleLowerCase() === "false")\n return "false";\n if (ariaInvalid === "true" || ariaInvalid === "grammar" || ariaInvalid === "spelling")\n return ariaInvalid;\n return "true";\n}\nfunction getValidityInvalid(element) {\n if ("validity" in element) {\n const validity = element.validity;\n return (validity == null ? void 0 : validity.valid) === false;\n }\n return false;\n}\nfunction getElementAccessibleErrorMessage(element) {\n const cache = cacheAccessibleErrorMessage;\n let accessibleErrorMessage = cacheAccessibleErrorMessage == null ? void 0 : cacheAccessibleErrorMessage.get(element);\n if (accessibleErrorMessage === void 0) {\n accessibleErrorMessage = "";\n const isAriaInvalid = getAriaInvalid(element) !== "false";\n const isValidityInvalid = getValidityInvalid(element);\n if (isAriaInvalid || isValidityInvalid) {\n const errorMessageId = element.getAttribute("aria-errormessage");\n const errorMessages = getIdRefs(element, errorMessageId);\n const parts = errorMessages.map((errorMessage) => asFlatString(\n getTextAlternativeInternal(errorMessage, {\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: errorMessage, hidden: isElementHiddenForAria(errorMessage) }\n }).text\n ));\n accessibleErrorMessage = parts.join(" ").trim();\n }\n cache == null ? void 0 : cache.set(element, accessibleErrorMessage);\n }\n return accessibleErrorMessage;\n}\nfunction insideTargetElement(options) {\n return options.embeddedInTargetElement === "self" || options.embeddedInTargetElement === "descendant";\n}\nfunction getTextAlternativeInternal(element, options) {\n var _a, _b, _c, _d, _e;\n if (options.visitedElements.has(element))\n return emptyCompositeString();\n const childOptions = {\n ...options,\n embeddedInTargetElement: options.embeddedInTargetElement === "self" ? "descendant" : options.embeddedInTargetElement\n };\n if (!options.includeHidden) {\n const isEmbeddedInHiddenReferenceTraversal = !!((_a = options.embeddedInLabelledBy) == null ? void 0 : _a.hidden) || !!((_b = options.embeddedInDescribedBy) == null ? void 0 : _b.hidden) || !!((_c = options.embeddedInNativeTextAlternative) == null ? void 0 : _c.hidden) || !!((_d = options.embeddedInLabel) == null ? void 0 : _d.hidden);\n if (isElementIgnoredForAria(element) || !isEmbeddedInHiddenReferenceTraversal && isElementHiddenForAria(element)) {\n options.visitedElements.add(element);\n return emptyCompositeString();\n }\n }\n const labelledBy = getAriaLabelledByElements(element);\n if (!options.embeddedInLabelledBy) {\n const accessibleName = joinCompositeString((labelledBy || []).map((ref) => getTextAlternativeInternal(ref, {\n ...options,\n embeddedInLabelledBy: { element: ref, hidden: isElementHiddenForAria(ref) },\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0,\n embeddedInLabel: void 0,\n embeddedInNativeTextAlternative: void 0\n })), " ", options.collectElements);\n if (accessibleName.text) {\n if (options.outDerivedFromContent && insideTargetElement(options) && (labelledBy || []).some((ref) => ref === element || element.contains(ref)))\n options.outDerivedFromContent.value = true;\n return accessibleName;\n }\n }\n const role = getAriaRole(element) || "";\n const tagName = elementSafeTagName(element);\n if (!!options.embeddedInLabel || !!options.embeddedInLabelledBy || options.embeddedInTargetElement === "descendant") {\n const isOwnLabel = [...element.labels || []].includes(element);\n const isOwnLabelledBy = (labelledBy || []).includes(element);\n if (!isOwnLabel && !isOwnLabelledBy) {\n if (role === "textbox" || role === "searchbox") {\n options.visitedElements.add(element);\n if (tagName === "INPUT" || tagName === "TEXTAREA")\n return compositeString(element.value, element, options.collectElements);\n return compositeString(element.textContent, element, options.collectElements);\n }\n if (["combobox", "listbox"].includes(role)) {\n options.visitedElements.add(element);\n let selectedOptions;\n if (tagName === "SELECT") {\n selectedOptions = [...element.selectedOptions];\n if (!selectedOptions.length && element.options.length)\n selectedOptions.push(element.options[0]);\n } else {\n const listbox = role === "combobox" ? queryInAriaOwned(element, "*").find((e) => getAriaRole(e) === "listbox") : element;\n selectedOptions = listbox ? queryInAriaOwned(listbox, \'[aria-selected="true"]\').filter((e) => getAriaRole(e) === "option") : [];\n }\n if (!selectedOptions.length && tagName === "INPUT") {\n return compositeString(element.value, element, options.collectElements);\n }\n return joinCompositeString(selectedOptions.map((option) => getTextAlternativeInternal(option, childOptions)), " ", options.collectElements);\n }\n if (["progressbar", "scrollbar", "slider", "spinbutton", "meter"].includes(role)) {\n options.visitedElements.add(element);\n if (element.hasAttribute("aria-valuetext"))\n return compositeString(element.getAttribute("aria-valuetext"), element, options.collectElements);\n if (element.hasAttribute("aria-valuenow"))\n return compositeString(element.getAttribute("aria-valuenow"), element, options.collectElements);\n return compositeString(element.getAttribute("value"), element, options.collectElements);\n }\n if (["menu"].includes(role)) {\n options.visitedElements.add(element);\n return emptyCompositeString();\n }\n }\n }\n const ariaLabel = element.getAttribute("aria-label") || "";\n if (trimFlatString(ariaLabel)) {\n options.visitedElements.add(element);\n return compositeString(ariaLabel, element, options.collectElements);\n }\n if (!["presentation", "none"].includes(role)) {\n if (tagName === "INPUT" && ["button", "submit", "reset"].includes(element.type)) {\n options.visitedElements.add(element);\n const value = element.value || "";\n if (trimFlatString(value))\n return compositeString(value, element, options.collectElements);\n if (element.type === "submit")\n return compositeString("Submit", element, options.collectElements);\n if (element.type === "reset")\n return compositeString("Reset", element, options.collectElements);\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "INPUT" && element.type === "file") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return compositeString("Choose File", element, options.collectElements);\n }\n if (tagName === "INPUT" && element.type === "image") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return compositeString(alt, element, options.collectElements);\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return compositeString(title, element, options.collectElements);\n return compositeString("Submit", element, options.collectElements);\n }\n if (!labelledBy && tagName === "BUTTON") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n }\n if (!labelledBy && tagName === "OUTPUT") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return compositeString(element.getAttribute("title") || "", element, options.collectElements);\n }\n if (!labelledBy && (tagName === "TEXTAREA" || tagName === "SELECT" || tagName === "INPUT" || tagName === "METER" || tagName === "PROGRESS")) {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const usePlaceholder = tagName === "INPUT" && ["text", "password", "number", "search", "tel", "email", "url"].includes(element.type) || tagName === "TEXTAREA";\n const placeholder = element.getAttribute("placeholder") || "";\n const title = element.getAttribute("title") || "";\n if (!usePlaceholder || title)\n return compositeString(title, element, options.collectElements);\n return compositeString(placeholder, element, options.collectElements);\n }\n if (!labelledBy && tagName === "FIELDSET") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "LEGEND") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (!labelledBy && tagName === "FIGURE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "FIGCAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "IMG") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return compositeString(alt, element, options.collectElements);\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "TABLE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "CAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const summary = element.getAttribute("summary") || "";\n if (summary)\n return compositeString(summary, element, options.collectElements);\n }\n if (tagName === "AREA") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return compositeString(alt, element, options.collectElements);\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "SVG" || element.ownerSVGElement) {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "TITLE" && child.ownerSVGElement) {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInLabelledBy: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n }\n if (element.ownerSVGElement && tagName === "A") {\n const title = element.getAttribute("xlink:title") || "";\n if (trimFlatString(title)) {\n options.visitedElements.add(element);\n return compositeString(title, element, options.collectElements);\n }\n }\n }\n const shouldNameFromContentForSummary = tagName === "SUMMARY" && !["presentation", "none"].includes(role);\n if (allowsNameFromContent(role, options.embeddedInTargetElement === "descendant") || shouldNameFromContentForSummary || !!options.embeddedInLabelledBy || !!options.embeddedInDescribedBy || !!options.embeddedInLabel || !!options.embeddedInNativeTextAlternative) {\n options.visitedElements.add(element);\n const accessibleName = innerAccumulatedElementText(element, childOptions);\n const maybeTrimmedAccessibleName = options.embeddedInTargetElement === "self" ? trimFlatString(accessibleName.text) : accessibleName.text;\n if (maybeTrimmedAccessibleName) {\n if (options.outDerivedFromContent && insideTargetElement(options) && trimFlatString(accessibleName.text))\n options.outDerivedFromContent.value = true;\n (_e = accessibleName.elements) == null ? void 0 : _e.add(element);\n return accessibleName;\n }\n }\n if (!["presentation", "none"].includes(role) || tagName === "IFRAME" || tagName === "FRAME") {\n options.visitedElements.add(element);\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return compositeString(title, element, options.collectElements);\n }\n options.visitedElements.add(element);\n return emptyCompositeString();\n}\nfunction innerAccumulatedElementText(element, options) {\n const tokens = [];\n const elements = options.collectElements ? /* @__PURE__ */ new Set() : void 0;\n const visit = (node, skipSlotted) => {\n var _a;\n if (skipSlotted && node.assignedSlot)\n return;\n if (node.nodeType === 1) {\n const display = ((_a = getElementComputedStyle(node)) == null ? void 0 : _a.display) || "inline";\n const childComposite = getTextAlternativeInternal(node, options);\n let token = childComposite.text;\n for (const contributor of childComposite.elements || [])\n elements == null ? void 0 : elements.add(contributor);\n if (display !== "inline" || node.nodeName === "BR")\n token = " " + token + " ";\n tokens.push(token);\n } else if (node.nodeType === 3) {\n tokens.push(node.textContent || "");\n }\n };\n tokens.push(getCSSContent(element, "::before") || "");\n const content = getCSSContent(element);\n if (content !== void 0) {\n tokens.push(content);\n } else {\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(child, false);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling)\n visit(child, true);\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(child, true);\n }\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns")))\n visit(owned, true);\n }\n }\n tokens.push(getCSSContent(element, "::after") || "");\n return { text: tokens.join(""), elements };\n}\nvar kAriaSelectedRoles = ["gridcell", "option", "row", "tab", "rowheader", "columnheader", "treeitem"];\nfunction getAriaSelected(element) {\n if (elementSafeTagName(element) === "OPTION")\n return element.selected;\n if (kAriaSelectedRoles.includes(getAriaRole(element) || ""))\n return getAriaBoolean(element.getAttribute("aria-selected")) === true;\n return false;\n}\nvar kAriaCheckedRoles = ["checkbox", "menuitemcheckbox", "option", "radio", "switch", "menuitemradio", "treeitem"];\nfunction getAriaChecked(element) {\n const result = getChecked(element, true);\n return result === "error" ? false : result;\n}\nfunction getCheckedAllowMixed(element) {\n return getChecked(element, true);\n}\nfunction getCheckedWithoutMixed(element) {\n const result = getChecked(element, false);\n return result;\n}\nfunction getChecked(element, allowMixed) {\n const tagName = elementSafeTagName(element);\n if (allowMixed && tagName === "INPUT" && element.indeterminate)\n return "mixed";\n if (tagName === "INPUT" && ["checkbox", "radio"].includes(element.type))\n return element.checked;\n if (kAriaCheckedRoles.includes(getAriaRole(element) || "")) {\n const checked = element.getAttribute("aria-checked");\n if (checked === "true")\n return true;\n if (allowMixed && checked === "mixed")\n return "mixed";\n return false;\n }\n return "error";\n}\nvar kAriaReadonlyRoles = ["checkbox", "combobox", "grid", "gridcell", "listbox", "radiogroup", "slider", "spinbutton", "textbox", "columnheader", "rowheader", "searchbox", "switch", "treegrid"];\nfunction getReadonly(element) {\n const tagName = elementSafeTagName(element);\n if (["INPUT", "TEXTAREA", "SELECT"].includes(tagName))\n return element.hasAttribute("readonly");\n if (kAriaReadonlyRoles.includes(getAriaRole(element) || ""))\n return element.getAttribute("aria-readonly") === "true";\n if (element.isContentEditable)\n return false;\n return "error";\n}\nvar kAriaPressedRoles = ["button"];\nfunction getAriaPressed(element) {\n if (kAriaPressedRoles.includes(getAriaRole(element) || "")) {\n const pressed = element.getAttribute("aria-pressed");\n if (pressed === "true")\n return true;\n if (pressed === "mixed")\n return "mixed";\n }\n return false;\n}\nvar kAriaExpandedRoles = ["application", "button", "checkbox", "combobox", "gridcell", "link", "listbox", "menuitem", "row", "rowheader", "tab", "treeitem", "columnheader", "menuitemcheckbox", "menuitemradio", "rowheader", "switch"];\nfunction getAriaExpanded(element) {\n if (elementSafeTagName(element) === "DETAILS")\n return element.open;\n if (kAriaExpandedRoles.includes(getAriaRole(element) || "")) {\n const expanded = element.getAttribute("aria-expanded");\n if (expanded === null)\n return void 0;\n if (expanded === "true")\n return true;\n return false;\n }\n return void 0;\n}\nvar kAriaLevelRoles = ["heading", "listitem", "row", "treeitem"];\nfunction getAriaLevel(element) {\n const native = { "H1": 1, "H2": 2, "H3": 3, "H4": 4, "H5": 5, "H6": 6 }[elementSafeTagName(element)];\n if (native)\n return native;\n if (kAriaLevelRoles.includes(getAriaRole(element) || "")) {\n const attr = element.getAttribute("aria-level");\n const value = attr === null ? Number.NaN : Number(attr);\n if (Number.isInteger(value) && value >= 1)\n return value;\n }\n return 0;\n}\nvar kAriaDisabledRoles = ["application", "button", "composite", "gridcell", "group", "input", "link", "menuitem", "scrollbar", "separator", "tab", "checkbox", "columnheader", "combobox", "grid", "listbox", "menu", "menubar", "menuitemcheckbox", "menuitemradio", "option", "radio", "radiogroup", "row", "rowheader", "searchbox", "select", "slider", "spinbutton", "switch", "tablist", "textbox", "toolbar", "tree", "treegrid", "treeitem"];\nfunction getAriaDisabled(element) {\n return isNativelyDisabled(element) || hasExplicitAriaDisabled(element);\n}\nfunction isNativelyDisabled(element) {\n const isNativeFormControl = ["BUTTON", "INPUT", "SELECT", "TEXTAREA", "OPTION", "OPTGROUP"].includes(elementSafeTagName(element));\n return isNativeFormControl && (element.hasAttribute("disabled") || belongsToDisabledOptGroup(element) || belongsToDisabledFieldSet(element));\n}\nfunction belongsToDisabledOptGroup(element) {\n return elementSafeTagName(element) === "OPTION" && !!element.closest("OPTGROUP[DISABLED]");\n}\nfunction belongsToDisabledFieldSet(element) {\n const fieldSetElement = element == null ? void 0 : element.closest("FIELDSET[DISABLED]");\n if (!fieldSetElement)\n return false;\n const legendElement = fieldSetElement.querySelector(":scope > LEGEND");\n return !legendElement || !legendElement.contains(element);\n}\nfunction hasExplicitAriaDisabled(element) {\n if (!kAriaDisabledRoles.includes(getAriaRole(element) || ""))\n return false;\n return hasAriaDisabledInChain(element);\n}\nfunction hasAriaDisabledInChain(element) {\n let result = cacheAriaDisabled == null ? void 0 : cacheAriaDisabled.get(element);\n if (result === void 0) {\n const attribute = (element.getAttribute("aria-disabled") || "").toLowerCase();\n if (attribute === "true") {\n result = true;\n } else if (attribute === "false") {\n result = false;\n } else {\n const parent = parentElementOrShadowHost(element);\n result = parent ? hasAriaDisabledInChain(parent) : false;\n }\n cacheAriaDisabled == null ? void 0 : cacheAriaDisabled.set(element, result);\n }\n return result;\n}\nfunction getAccessibleNameFromAssociatedLabels(labels, options) {\n return joinCompositeString([...labels].map((label) => getTextAlternativeInternal(label, {\n ...options,\n embeddedInLabel: { element: label, hidden: isElementHiddenForAria(label) },\n embeddedInNativeTextAlternative: void 0,\n embeddedInLabelledBy: void 0,\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0\n })).filter((accessibleName) => !!accessibleName.text), " ", options.collectElements);\n}\nfunction receivesPointerEvents(element) {\n const cache = cachePointerEvents;\n let e = element;\n let result;\n const parents = [];\n for (; e; e = parentElementOrShadowHost(e)) {\n const cached = cache.get(e);\n if (cached !== void 0) {\n result = cached;\n break;\n }\n parents.push(e);\n const style = getElementComputedStyle(e);\n if (!style) {\n result = true;\n break;\n }\n const value = style.pointerEvents;\n if (value) {\n result = value !== "none";\n break;\n }\n }\n if (result === void 0)\n result = true;\n for (const parent of parents)\n cache.set(parent, result);\n return result;\n}\nvar cacheAccessibleName;\nvar cacheAccessibleNameHidden;\nvar cacheAccessibleNameText;\nvar cacheAccessibleNameTextHidden;\nvar cacheAccessibleDescription;\nvar cacheAccessibleDescriptionHidden;\nvar cacheAccessibleErrorMessage;\nvar cacheIsHidden;\nvar cachePseudoContent;\nvar cachePseudoContentBefore;\nvar cachePseudoContentAfter;\nvar cachePointerEvents;\nvar cacheAriaRole;\nvar cacheAriaDisabled;\nvar cachesCounter2 = 0;\nfunction beginAriaCaches() {\n beginDOMCaches();\n ++cachesCounter2;\n cacheAriaRole != null ? cacheAriaRole : cacheAriaRole = /* @__PURE__ */ new Map();\n cacheAriaDisabled != null ? cacheAriaDisabled : cacheAriaDisabled = /* @__PURE__ */ new Map();\n cacheAccessibleName != null ? cacheAccessibleName : cacheAccessibleName = /* @__PURE__ */ new Map();\n cacheAccessibleNameHidden != null ? cacheAccessibleNameHidden : cacheAccessibleNameHidden = /* @__PURE__ */ new Map();\n cacheAccessibleNameText != null ? cacheAccessibleNameText : cacheAccessibleNameText = /* @__PURE__ */ new Map();\n cacheAccessibleNameTextHidden != null ? cacheAccessibleNameTextHidden : cacheAccessibleNameTextHidden = /* @__PURE__ */ new Map();\n cacheAccessibleDescription != null ? cacheAccessibleDescription : cacheAccessibleDescription = /* @__PURE__ */ new Map();\n cacheAccessibleDescriptionHidden != null ? cacheAccessibleDescriptionHidden : cacheAccessibleDescriptionHidden = /* @__PURE__ */ new Map();\n cacheAccessibleErrorMessage != null ? cacheAccessibleErrorMessage : cacheAccessibleErrorMessage = /* @__PURE__ */ new Map();\n cacheIsHidden != null ? cacheIsHidden : cacheIsHidden = /* @__PURE__ */ new Map();\n cachePseudoContent != null ? cachePseudoContent : cachePseudoContent = /* @__PURE__ */ new Map();\n cachePseudoContentBefore != null ? cachePseudoContentBefore : cachePseudoContentBefore = /* @__PURE__ */ new Map();\n cachePseudoContentAfter != null ? cachePseudoContentAfter : cachePseudoContentAfter = /* @__PURE__ */ new Map();\n cachePointerEvents != null ? cachePointerEvents : cachePointerEvents = /* @__PURE__ */ new Map();\n}\nfunction endAriaCaches() {\n if (!--cachesCounter2) {\n cacheAccessibleName = void 0;\n cacheAccessibleNameHidden = void 0;\n cacheAccessibleNameText = void 0;\n cacheAccessibleNameTextHidden = void 0;\n cacheAccessibleDescription = void 0;\n cacheAccessibleDescriptionHidden = void 0;\n cacheAccessibleErrorMessage = void 0;\n cacheIsHidden = void 0;\n cachePseudoContent = void 0;\n cachePseudoContentBefore = void 0;\n cachePseudoContentAfter = void 0;\n cachePointerEvents = void 0;\n cacheAriaRole = void 0;\n cacheAriaDisabled = void 0;\n }\n endDOMCaches();\n}\nvar inputTypeToRole = {\n "button": "button",\n "checkbox": "checkbox",\n "image": "button",\n "number": "spinbutton",\n "radio": "radio",\n "range": "slider",\n "reset": "button",\n "submit": "button"\n};\nfunction emptyCompositeString() {\n return { text: "" };\n}\nfunction compositeString(text, element, collectElements) {\n const elements = text && collectElements ? /* @__PURE__ */ new Set([element]) : void 0;\n return { text: text || "", elements };\n}\nfunction joinCompositeString(parts, separator, collectElements) {\n let elements;\n if (collectElements) {\n elements = /* @__PURE__ */ new Set();\n for (const part of parts) {\n for (const element of part.elements || [])\n elements.add(element);\n }\n }\n return { text: parts.map((part) => part.text).join(separator), elements };\n}\n\n// packages/injected/src/ariaSnapshot.ts\nvar lastRef = 0;\nfunction toInternalOptions(options) {\n const renderBoxes = options.boxes;\n if (options.mode === "ai") {\n return {\n visibility: "ariaOrVisible",\n refs: "interactable",\n refPrefix: options.refPrefix,\n includeGenericRole: true,\n renderActive: !options.doNotRenderActive,\n renderCursorPointer: true,\n renderBoxes\n };\n }\n if (options.mode === "autoexpect") {\n return { visibility: "ariaAndVisible", refs: "none", renderBoxes };\n }\n return { visibility: "aria", refs: "none", renderBoxes };\n}\nfunction generateAriaTree(rootElement, publicOptions) {\n const options = toInternalOptions(publicOptions);\n const visited = /* @__PURE__ */ new Set();\n const nameSourceElements = /* @__PURE__ */ new Map();\n const snapshot = {\n root: { role: "fragment", name: "", children: [], props: {}, box: computeBox(rootElement), receivesPointerEvents: true },\n info: /* @__PURE__ */ new Map(),\n refs: /* @__PURE__ */ new Map(),\n iframeRefs: []\n };\n setAriaNodeElement(snapshot.root, rootElement);\n const visit = (ariaNode, node, parentElementVisible) => {\n var _a;\n if (visited.has(node))\n return;\n visited.add(node);\n if (node.nodeType === Node.TEXT_NODE && node.nodeValue) {\n if (!parentElementVisible)\n return;\n const text = node.nodeValue;\n if (ariaNode.role !== "textbox" && text)\n ariaNode.children.push(node.nodeValue || "");\n return;\n }\n if (node.nodeType !== Node.ELEMENT_NODE)\n return;\n const element = node;\n const isElementVisibleForAria = !isElementHiddenForAria(element);\n let visible = isElementVisibleForAria;\n if (options.visibility === "ariaOrVisible")\n visible = isElementVisibleForAria || isElementVisible(element);\n if (options.visibility === "ariaAndVisible")\n visible = isElementVisibleForAria && isElementVisible(element);\n if (options.visibility === "aria" && !visible)\n return;\n const ariaChildren = [];\n if (element.hasAttribute("aria-owns")) {\n const ids = element.getAttribute("aria-owns").split(/\\s+/);\n for (const id of ids) {\n const ownedElement = rootElement.ownerDocument.getElementById(id);\n if (ownedElement)\n ariaChildren.push(ownedElement);\n }\n }\n const childAriaNode = visible ? toAriaNode(element, options, nameSourceElements) : null;\n if (childAriaNode && ((_a = element.getAttribute("aria-hidden")) == null ? void 0 : _a.toLowerCase()) === "true")\n childAriaNode.props["aria-hidden"] = "true";\n let elementInfo;\n if (childAriaNode) {\n if (childAriaNode.ref) {\n elementInfo = { element, nameFromContentRefs: [] };\n snapshot.info.set(childAriaNode.ref, elementInfo);\n snapshot.refs.set(element, childAriaNode.ref);\n if (childAriaNode.role === "iframe")\n snapshot.iframeRefs.push(childAriaNode.ref);\n }\n ariaNode.children.push(childAriaNode);\n }\n processElement(childAriaNode || ariaNode, element, ariaChildren, visible);\n if (elementInfo) {\n for (const contributor of nameSourceElements.get(childAriaNode) || []) {\n const ref = snapshot.refs.get(contributor);\n if (ref && ref !== childAriaNode.ref)\n elementInfo.nameFromContentRefs.push(ref);\n }\n }\n };\n function processElement(ariaNode, element, ariaChildren, parentElementVisible) {\n var _a;\n const display = ((_a = getElementComputedStyle(element)) == null ? void 0 : _a.display) || "inline";\n const treatAsBlock = display !== "inline" || element.nodeName === "BR" ? " " : "";\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n ariaNode.children.push(getCSSContent(element, "::before") || "");\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(ariaNode, child, parentElementVisible);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (!child.assignedSlot)\n visit(ariaNode, child, parentElementVisible);\n }\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(ariaNode, child, parentElementVisible);\n }\n }\n for (const child of ariaChildren)\n visit(ariaNode, child, parentElementVisible);\n ariaNode.children.push(getCSSContent(element, "::after") || "");\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n if (ariaNode.children.length === 1 && ariaNode.name === ariaNode.children[0])\n ariaNode.children = [];\n if (ariaNode.role === "link" && element.hasAttribute("href")) {\n const href = element.getAttribute("href");\n ariaNode.props["url"] = truncateDataUrl(href);\n }\n if (ariaNode.role === "textbox" && element.hasAttribute("placeholder") && element.getAttribute("placeholder") !== ariaNode.name) {\n const placeholder = element.getAttribute("placeholder");\n ariaNode.props["placeholder"] = placeholder;\n }\n }\n beginAriaCaches();\n try {\n visit(snapshot.root, rootElement, true);\n } finally {\n endAriaCaches();\n }\n distillAriaSnapshot(snapshot, publicOptions);\n return snapshot;\n}\nfunction computeAriaRef(ariaNode, options) {\n var _a;\n if (options.refs === "none")\n return;\n if (options.refs === "interactable" && (!ariaNode.box.visible || !ariaNode.receivesPointerEvents))\n return;\n const element = ariaNodeElement(ariaNode);\n let ariaRef = element._ariaRef;\n if (!ariaRef || ariaRef.role !== ariaNode.role || ariaRef.name !== ariaNode.name) {\n ariaRef = { role: ariaNode.role, name: ariaNode.name, ref: ((_a = options.refPrefix) != null ? _a : "") + "e" + ++lastRef };\n element._ariaRef = ariaRef;\n }\n ariaNode.ref = ariaRef.ref;\n}\nfunction toAriaNode(element, options, nameSourceElements) {\n var _a;\n const active = element.ownerDocument.activeElement === element && element.ownerDocument.hasFocus();\n if (element.nodeName === "IFRAME" || element.nodeName === "FRAME") {\n const ariaNode = {\n role: "iframe",\n name: "",\n children: [],\n props: {},\n box: computeBox(element),\n receivesPointerEvents: true,\n active\n };\n setAriaNodeElement(ariaNode, element);\n computeAriaRef(ariaNode, options);\n return ariaNode;\n }\n const defaultRole = options.includeGenericRole ? "generic" : null;\n const role = (_a = getAriaRole(element)) != null ? _a : defaultRole;\n if (!role || role === "presentation" || role === "none")\n return null;\n const name = getElementAccessibleName(element, false);\n const receivesPointerEvents2 = receivesPointerEvents(element);\n const box = computeBox(element);\n if (role === "generic" && box.inline && element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE)\n return null;\n const result = {\n role,\n name: normalizeWhiteSpace(name.text),\n children: [],\n props: {},\n box,\n receivesPointerEvents: receivesPointerEvents2,\n active\n };\n setAriaNodeElement(result, element);\n nameSourceElements.set(result, name.elements);\n computeAriaRef(result, options);\n if (kAriaCheckedRoles.includes(role))\n result.checked = getAriaChecked(element);\n if (kAriaDisabledRoles.includes(role))\n result.disabled = getAriaDisabled(element);\n if (kAriaExpandedRoles.includes(role))\n result.expanded = getAriaExpanded(element);\n if (kAriaInvalidRoles.includes(role)) {\n const invalid = getAriaInvalid(element);\n result.invalid = invalid === "false" ? false : invalid === "true" ? true : invalid;\n }\n if (kAriaLevelRoles.includes(role))\n result.level = getAriaLevel(element);\n if (kAriaPressedRoles.includes(role))\n result.pressed = getAriaPressed(element);\n if (kAriaSelectedRoles.includes(role))\n result.selected = getAriaSelected(element);\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n if (element.type !== "checkbox" && element.type !== "radio" && element.type !== "file")\n result.children = [element.value];\n }\n return result;\n}\nfunction matchesStringOrRegex(text, template) {\n if (!template)\n return true;\n if (!text)\n return false;\n if (typeof template === "string")\n return text === template;\n return !!text.match(new RegExp(template.pattern));\n}\nfunction matchesTextValue(text, template) {\n if (!(template == null ? void 0 : template.normalized))\n return true;\n if (!text)\n return false;\n if (text === template.normalized)\n return true;\n if (text === template.raw)\n return true;\n const regex = cachedRegex(template);\n if (regex)\n return !!text.match(regex);\n return false;\n}\nvar cachedRegexSymbol = /* @__PURE__ */ Symbol("cachedRegex");\nfunction cachedRegex(template) {\n if (template[cachedRegexSymbol] !== void 0)\n return template[cachedRegexSymbol];\n const { raw } = template;\n const canBeRegex = raw.startsWith("/") && raw.endsWith("/") && raw.length > 1;\n let regex;\n try {\n regex = canBeRegex ? new RegExp(raw.slice(1, -1)) : null;\n } catch (e) {\n regex = null;\n }\n template[cachedRegexSymbol] = regex;\n return regex;\n}\nfunction matchesExpectAriaTemplate(rootElement, template) {\n const snapshot = generateAriaTree(rootElement, { mode: "default" });\n const matches = matchesNodeDeep(snapshot.root, template, false, false);\n const { json } = renderAriaTreeAsJSON(snapshot, { mode: "default" });\n return {\n matches,\n received: {\n raw: renderAriaSnapshotAsYaml(json),\n regex: renderAriaSnapshotAsYaml(json, { convertStringsToRegex: true })\n }\n };\n}\nfunction getAllElementsMatchingExpectAriaTemplate(rootElement, template) {\n const root = generateAriaTree(rootElement, { mode: "default" }).root;\n const matches = matchesNodeDeep(root, template, true, false);\n return matches.map((n) => ariaNodeElement(n));\n}\nfunction matchesNode(node, template, isDeepEqual) {\n var _a;\n if (typeof node === "string" && template.kind === "text")\n return matchesTextValue(node, template.text);\n if (node === null || typeof node !== "object" || template.kind !== "role")\n return false;\n if (template.role !== "fragment" && template.role !== node.role)\n return false;\n if (template.checked !== void 0 && template.checked !== node.checked)\n return false;\n if (template.disabled !== void 0 && template.disabled !== node.disabled)\n return false;\n if (template.expanded !== void 0 && template.expanded !== node.expanded)\n return false;\n if (template.invalid !== void 0 && template.invalid !== node.invalid)\n return false;\n if (template.level !== void 0 && template.level !== node.level)\n return false;\n if (template.pressed !== void 0 && template.pressed !== node.pressed)\n return false;\n if (template.selected !== void 0 && template.selected !== node.selected)\n return false;\n if (!matchesStringOrRegex(node.name, template.name))\n return false;\n if (!matchesTextValue(node.props.url, (_a = template.props) == null ? void 0 : _a.url))\n return false;\n if (template.containerMode === "contain")\n return containsList(node.children || [], template.children || []);\n if (template.containerMode === "equal")\n return listEqual(node.children || [], template.children || [], false);\n if (template.containerMode === "deep-equal" || isDeepEqual)\n return listEqual(node.children || [], template.children || [], true);\n return containsList(node.children || [], template.children || []);\n}\nfunction listEqual(children, template, isDeepEqual) {\n if (template.length !== children.length)\n return false;\n for (let i = 0; i < template.length; ++i) {\n if (!matchesNode(children[i], template[i], isDeepEqual))\n return false;\n }\n return true;\n}\nfunction containsList(children, template) {\n if (template.length > children.length)\n return false;\n const cc = children.slice();\n const tt = template.slice();\n for (const t of tt) {\n let c = cc.shift();\n while (c) {\n if (matchesNode(c, t, false))\n break;\n c = cc.shift();\n }\n if (!c)\n return false;\n }\n return true;\n}\nfunction matchesNodeDeep(root, template, collectAll, isDeepEqual) {\n const results = [];\n const visit = (node, parent) => {\n if (matchesNode(node, template, isDeepEqual)) {\n const result = typeof node === "string" ? parent : node;\n if (result)\n results.push(result);\n return !collectAll;\n }\n if (typeof node === "string")\n return false;\n for (const child of node.children || []) {\n if (visit(child, node))\n return true;\n }\n return false;\n };\n visit(root, null);\n return results;\n}\nfunction renderAriaTreeAsJSON(ariaSnapshot, publicOptions) {\n const options = toInternalOptions(publicOptions);\n const iframeDepths = {};\n const visit = (ariaNode, depth, renderCursorPointer) => {\n if (ariaNode.role === "iframe" && ariaNode.ref)\n iframeDepths[ariaNode.ref] = depth;\n const node = { role: ariaNode.role };\n if (ariaNode.name)\n node.name = ariaNode.name;\n if (ariaNode.checked === "mixed" || ariaNode.checked === true)\n node.checked = ariaNode.checked;\n if (ariaNode.disabled)\n node.disabled = true;\n if (ariaNode.expanded)\n node.expanded = true;\n if (ariaNode.active && options.renderActive)\n node.active = true;\n if (ariaNode.invalid)\n node.invalid = ariaNode.invalid;\n if (ariaNode.level)\n node.level = ariaNode.level;\n if (ariaNode.pressed === "mixed" || ariaNode.pressed === true)\n node.pressed = ariaNode.pressed;\n if (ariaNode.selected === true)\n node.selected = true;\n if (ariaNode.ref) {\n node.ref = ariaNode.ref;\n if (renderCursorPointer && hasPointerCursor(ariaNode))\n node.cursor = "pointer";\n }\n if (options.renderBoxes) {\n const element = ariaNodeElement(ariaNode);\n if (element) {\n const r = element.getBoundingClientRect();\n node.box = { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };\n }\n }\n if (ariaNode.props.url !== void 0)\n node.url = ariaNode.props.url;\n if (ariaNode.props.placeholder !== void 0)\n node.placeholder = ariaNode.props.placeholder;\n if (ariaNode.props["aria-hidden"] !== void 0)\n node.ariaHidden = true;\n const singleTextChild = ariaNode.children.length === 1 && typeof ariaNode.children[0] === "string" ? ariaNode.children[0] : void 0;\n const isAtDepthLimit = !!publicOptions.depth && depth === publicOptions.depth;\n if (singleTextChild !== void 0) {\n node.text = singleTextChild;\n } else if (!isAtDepthLimit && ariaNode.children.length) {\n const inCursorPointer = !!ariaNode.ref && renderCursorPointer && hasPointerCursor(ariaNode);\n node.children = ariaNode.children.map((child) => {\n if (typeof child === "string")\n return child;\n return visit(child, depth + 1, renderCursorPointer && !inCursorPointer);\n });\n }\n return node;\n };\n const json = [];\n const nodesToRender = ariaSnapshot.root.role === "fragment" ? ariaSnapshot.root.children : [ariaSnapshot.root];\n for (const nodeToRender of nodesToRender) {\n if (typeof nodeToRender === "string")\n json.push({ role: "text", text: nodeToRender });\n else\n json.push(visit(nodeToRender, 0, !!options.renderCursorPointer));\n }\n return { json, iframeDepths };\n}\nvar elementSymbol = /* @__PURE__ */ Symbol("element");\nfunction ariaNodeElement(ariaNode) {\n return ariaNode[elementSymbol];\n}\nfunction setAriaNodeElement(ariaNode, element) {\n ariaNode[elementSymbol] = element;\n}\nfunction findNewElement(from, to) {\n const node = findNewNode(from, to);\n return node ? ariaNodeElement(node) : void 0;\n}\n\n// packages/injected/src/highlight.css?inline\nvar highlight_default = ":host{font-size:13px;font-family:system-ui,Ubuntu,Droid Sans,sans-serif;color:#333;color-scheme:light}svg{position:absolute;height:0}x-pw-tooltip{backdrop-filter:blur(5px);background-color:#fff;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:none;font-size:12.8px;font-weight:400;left:0;line-height:1.5;max-width:600px;position:absolute;top:0;padding:0;flex-direction:column;overflow:hidden}x-pw-tooltip-line{display:flex;max-width:600px;padding:6px;user-select:none;cursor:pointer}x-pw-tooltip-footer{display:flex;max-width:600px;padding:6px;user-select:none;color:#777}x-pw-dialog{background-color:#fff;pointer-events:auto;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:flex;flex-direction:column;position:absolute;z-index:10;font-size:13px}x-pw-dialog:not(.autosize){width:400px;height:150px}x-pw-dialog-body{display:flex;flex-direction:column;flex:auto}x-pw-dialog-body label{margin:5px 8px;display:flex;flex-direction:row;align-items:center}x-pw-highlight{position:absolute;top:0;left:0;width:0;height:0}x-pw-action-point{position:absolute;width:20px;height:20px;background:red;border-radius:10px;margin:-10px 0 0 -10px;z-index:2}x-pw-screencast-highlight,x-pw-screencast-point,x-pw-title{animation:pw-fade-out var(--pw-fade-duration) ease-out var(--pw-fade-delay, 0ms) forwards}x-pw-screencast-highlight,x-pw-screencast-point{position:absolute;pointer-events:none}x-pw-screencast-highlight{z-index:1}x-pw-screencast-point{width:0;height:0;overflow:visible;translate:-50% -50%;z-index:2}x-pw-action-cursor{position:absolute;width:14px;height:21px;pointer-events:none;z-index:4;filter:drop-shadow(0 1px 1.5px rgba(0,0,0,.35))}x-pw-action-cursor svg{width:100%;height:100%;position:static;overflow:visible}x-pw-title{position:absolute;backdrop-filter:blur(5px);background-color:#00000080;color:#fff;border-radius:6px;padding:6px;font-size:24px;line-height:1.4;white-space:nowrap;user-select:none;z-index:3}x-pw-user-overlays,x-pw-user-overlay{position:absolute;inset:0}@keyframes pw-fade-out{0%{opacity:1}to{opacity:0}}x-pw-separator{height:1px;margin:6px 9px;background:#949494e5}x-pw-tool-gripper{height:28px;width:24px;margin:2px 0;cursor:grab}x-pw-tool-gripper:active{cursor:grabbing}x-pw-tool-gripper>x-div{width:16px;height:16px;margin:6px 4px;clip-path:url(#icon-gripper);background-color:#555}x-pw-tools-list>label{display:flex;align-items:center;margin:0 10px;user-select:none}x-pw-tools-list{display:flex;width:100%;border-bottom:1px solid #dddddd}x-pw-tool-item{pointer-events:auto;height:28px;width:28px;border-radius:3px}x-pw-tool-item:not(.disabled){cursor:pointer}x-pw-tool-item:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.toggled{background-color:#8acae480}x-pw-tool-item.toggled:not(.disabled):hover{background-color:#8acae4c4}x-pw-tool-item>x-div{width:16px;height:16px;margin:6px;background-color:#3a3a3a}x-pw-tool-item.disabled>x-div{background-color:#61616180;cursor:default}x-pw-tool-item.record.toggled{background-color:transparent}x-pw-tool-item.record.toggled:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.record.toggled>x-div{background-color:#a1260d}x-pw-tool-item.record.disabled.toggled>x-div{opacity:.8}x-pw-tool-item.accept>x-div{background-color:#388a34}x-pw-tool-item.record>x-div{clip-path:url(#icon-circle-large-filled)}x-pw-tool-item.record.toggled>x-div{clip-path:url(#icon-stop-circle)}x-pw-tool-item.pick-locator>x-div{clip-path:url(#icon-inspect)}x-pw-tool-item.text>x-div{clip-path:url(#icon-whole-word)}x-pw-tool-item.visibility>x-div{clip-path:url(#icon-eye)}x-pw-tool-item.value>x-div{clip-path:url(#icon-symbol-constant)}x-pw-tool-item.snapshot>x-div{clip-path:url(#icon-gist)}x-pw-tool-item.accept>x-div{clip-path:url(#icon-check)}x-pw-tool-item.cancel>x-div{clip-path:url(#icon-close)}x-pw-tool-item.succeeded>x-div{clip-path:url(#icon-pass);background-color:#388a34!important}x-pw-overlay{position:absolute;top:0;max-width:min-content;z-index:2147483647;background:transparent;pointer-events:auto}x-pw-overlay x-pw-tools-list{background-color:#fffd;box-shadow:#0000001a 0 5px 5px;border-radius:3px;border-bottom:none}x-pw-overlay x-pw-tool-item{margin:2px}textarea.text-editor{font-family:system-ui,Ubuntu,Droid Sans,sans-serif;flex:auto;border:none;margin:6px 10px;color:#333;outline:1px solid transparent!important;resize:none;padding:0;font-size:13px}textarea.text-editor.does-not-match{outline:1px solid red!important}x-div{display:block}x-spacer{flex:auto}*{box-sizing:border-box}*[hidden]{display:none!important}x-locator-editor{flex:none;width:100%;height:60px;padding:4px;border-bottom:1px solid #dddddd;outline:1px solid transparent}x-locator-editor.does-not-match{outline:1px solid red}.CodeMirror{width:100%!important;height:100%!important}x-pw-action-list{flex:auto;display:flex;flex-direction:column;user-select:none}x-pw-action-item{padding:6px 10px;cursor:pointer;overflow:hidden}x-pw-action-item:hover{background-color:#f2f2f2}x-pw-action-item:last-child{border-bottom-left-radius:6px;border-bottom-right-radius:6px}\\n";\n\n// packages/injected/src/highlight.ts\nvar Highlight = class {\n constructor(injectedScript) {\n this._renderedEntries = [];\n this._screencastDecorations = [];\n this._userOverlays = /* @__PURE__ */ new Map();\n this._userOverlayHidden = false;\n this._language = "javascript";\n this._elementHighlights = [];\n this._injectedScript = injectedScript;\n const document = injectedScript.document;\n this._isUnderTest = injectedScript.isUnderTest;\n this._glassPaneElement = document.createElement("x-pw-glass");\n this._glassPaneElement.setAttribute("popover", "manual");\n this._glassPaneElement.style.inset = "0";\n this._glassPaneElement.style.width = "100%";\n this._glassPaneElement.style.height = "100%";\n this._glassPaneElement.style.maxWidth = "none";\n this._glassPaneElement.style.maxHeight = "none";\n this._glassPaneElement.style.padding = "0";\n this._glassPaneElement.style.margin = "0";\n this._glassPaneElement.style.border = "none";\n this._glassPaneElement.style.overflow = "visible";\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.display = "flex";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._actionCursorElement = document.createElement("x-pw-action-cursor");\n this._actionCursorElement.style.visibility = "hidden";\n this._actionCursorElement.appendChild(this._createCursorSvg(document));\n this._titleElement = document.createElement("x-pw-title");\n this._titleElement.setAttribute("hidden", "true");\n this._userOverlayContainer = document.createElement("x-pw-user-overlays");\n this._userOverlayContainer.setAttribute("hidden", "true");\n this._glassPaneShadow = this._glassPaneElement.attachShadow({ mode: this._isUnderTest ? "open" : "closed" });\n if (typeof this._glassPaneShadow.adoptedStyleSheets.push === "function") {\n const sheet = new this._injectedScript.window.CSSStyleSheet();\n sheet.replaceSync(highlight_default);\n this._glassPaneShadow.adoptedStyleSheets.push(sheet);\n } else {\n const styleElement = this._injectedScript.document.createElement("style");\n styleElement.textContent = highlight_default;\n this._glassPaneShadow.appendChild(styleElement);\n }\n this._glassPaneShadow.appendChild(this._actionCursorElement);\n this._glassPaneShadow.appendChild(this._titleElement);\n this._glassPaneShadow.appendChild(this._userOverlayContainer);\n }\n install() {\n if (!this._injectedScript.document.documentElement)\n return;\n if (!this._injectedScript.document.documentElement.contains(this._glassPaneElement) || this._glassPaneElement.nextElementSibling)\n this._injectedScript.document.documentElement.appendChild(this._glassPaneElement);\n this._bringToFront();\n }\n _bringToFront() {\n this._glassPaneElement.hidePopover();\n this._glassPaneElement.showPopover();\n }\n setLanguage(language) {\n this._language = language;\n }\n setElementHighlights(highlights) {\n const hadHighlights = this._elementHighlights.length > 0;\n this._elementHighlights = highlights;\n if (this._elementHighlights.length) {\n this._ensureElementHighlightRaf();\n } else if (hadHighlights) {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this.clearHighlight();\n }\n }\n _ensureElementHighlightRaf() {\n if (this._rafRequest)\n return;\n const tick = () => {\n const entries = [];\n const glassPanes = [...this._injectedScript.document.querySelectorAll("x-pw-glass")];\n for (const { selector, cssStyle } of this._elementHighlights) {\n let elements = [];\n try {\n elements = this._injectedScript.querySelectorAll(selector, this._injectedScript.document.documentElement);\n } catch {\n }\n elements = elements.filter((element) => !glassPanes.some((pane) => this._injectedScript.utils.isInsideScope(pane, element)));\n const locator = selector.parts.some((part) => part.name === "aria-template") ? void 0 : asLocator(this._language, stringifySelector(selector));\n const color = elements.length > 1 ? "#f6b26b7f" : "#6fa8dc7f";\n for (let i = 0; i < elements.length; ++i) {\n const suffix = elements.length > 1 ? ` [${i + 1} of ${elements.length}]` : "";\n entries.push({ element: elements[i], color, tooltipText: locator === void 0 ? void 0 : locator + suffix, cssStyle });\n }\n }\n this.updateHighlight(entries);\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n };\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n }\n uninstall() {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this._elementHighlights = [];\n this._clearUserOverlayTimer();\n this._glassPaneElement.remove();\n }\n showActionPoint(x, y) {\n if (!this._actionPointElement) {\n this._actionPointElement = this._injectedScript.document.createElement("x-pw-action-point");\n this._glassPaneShadow.appendChild(this._actionPointElement);\n }\n this._actionPointElement.style.top = y + "px";\n this._actionPointElement.style.left = x + "px";\n this._actionPointElement.hidden = false;\n }\n hideActionPoint() {\n if (this._actionPointElement)\n this._actionPointElement.hidden = true;\n }\n showScreencastHighlight(box, style, fadeDuration) {\n const element = this._createScreencastDecoration("x-pw-screencast-highlight", style, fadeDuration);\n element.style.left = box.x + "px";\n element.style.top = box.y + "px";\n element.style.width = box.width + "px";\n element.style.height = box.height + "px";\n }\n showScreencastPoint(x, y, style, fadeDuration) {\n const element = this._createScreencastDecoration("x-pw-screencast-point", style, fadeDuration);\n element.style.left = x + "px";\n element.style.top = y + "px";\n }\n hideScreencastDecorations() {\n for (const element of this._screencastDecorations)\n element.remove();\n this._screencastDecorations = [];\n }\n _createScreencastDecoration(name, style, fadeDuration) {\n const element = this._injectedScript.document.createElement(name);\n element.style.cssText = style;\n if (fadeDuration)\n element.style.setProperty("--pw-fade-duration", fadeDuration + "ms");\n this._glassPaneShadow.appendChild(element);\n this._screencastDecorations.push(element);\n return element;\n }\n moveActionCursor(x, y, fadeDuration) {\n var _a;\n const element = this._actionCursorElement;\n const from = element.getBoundingClientRect();\n const wasVisible = element.style.visibility === "visible";\n (_a = this._actionCursorAnimation) == null ? void 0 : _a.cancel();\n this._actionCursorAnimation = void 0;\n element.style.left = x + "px";\n element.style.top = y + "px";\n element.style.visibility = "visible";\n const dx = from.left - x;\n const dy = from.top - y;\n if (!wasVisible || !fadeDuration || Math.hypot(dx, dy) < 1)\n return;\n const duration = Math.max(80, Math.min(fadeDuration * 0.6, 400));\n this._actionCursorAnimation = element.animate(cursorPathKeyframes(dx, dy, x + y + dx + dy), { duration, easing: "cubic-bezier(0.5, 0, 0.3, 1)" });\n }\n restoreActionCursor(x, y) {\n if (this._actionCursorElement.style.visibility !== "visible")\n this.moveActionCursor(x, y);\n }\n hideActionCursor() {\n this._actionCursorElement.style.visibility = "hidden";\n }\n _createCursorSvg(document) {\n const svgNs = "http://www.w3.org/2000/svg";\n const svg = document.createElementNS(svgNs, "svg");\n svg.setAttribute("viewBox", "0 0 12 18");\n const path = document.createElementNS(svgNs, "path");\n path.setAttribute("d", "M0 0 L0 15.8 L3.9 12.4 L6.6 18.6 L8.9 17.6 L6.2 11.4 L11.2 11.4 Z");\n path.setAttribute("fill", "black");\n path.setAttribute("stroke", "white");\n path.setAttribute("stroke-width", "1.6");\n path.setAttribute("stroke-linejoin", "round");\n path.setAttribute("paint-order", "stroke");\n svg.appendChild(path);\n return svg;\n }\n showActionTitle(text, fadeDuration, position, style) {\n this._titleElement.textContent = text;\n this._titleElement.hidden = false;\n this._titleElement.style.cssText = style != null ? style : "";\n if (fadeDuration) {\n const fadeTime = fadeDuration / 4;\n this._titleElement.style.setProperty("--pw-fade-duration", fadeTime + "ms");\n this._titleElement.style.setProperty("--pw-fade-delay", fadeDuration - fadeTime + "ms");\n }\n switch (position) {\n case "top-left":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "top":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-left":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "bottom":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-right":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.right = "6px";\n break;\n case "top-right":\n default:\n this._titleElement.style.top = "6px";\n this._titleElement.style.right = "6px";\n break;\n }\n }\n hideActionTitle() {\n this._titleElement.hidden = true;\n }\n addUserOverlay(id, html) {\n const element = this._injectedScript.document.createElement("div");\n element.className = "x-pw-user-overlay";\n element.innerHTML = html;\n for (const script of element.querySelectorAll("script"))\n script.remove();\n for (const el of element.querySelectorAll("*")) {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith("on"))\n el.removeAttribute(attr.name);\n }\n }\n this._userOverlays.set(id, element);\n this._userOverlayContainer.appendChild(element);\n this._userOverlayContainer.hidden = this._userOverlayHidden;\n this._ensureUserOverlayTimer();\n return id;\n }\n getUserOverlay(id) {\n return this._userOverlays.get(id);\n }\n removeUserOverlay(id) {\n const element = this._userOverlays.get(id);\n if (element) {\n element.remove();\n this._userOverlays.delete(id);\n }\n if (this._userOverlays.size === 0) {\n this._userOverlayContainer.hidden = true;\n this._clearUserOverlayTimer();\n }\n }\n // Elements that enter the top layer later paint above the glass pane, so keep re-promoting it while overlays are showing.\n _ensureUserOverlayTimer() {\n if (this._userOverlayTimer !== void 0)\n return;\n const tick = () => {\n this.install();\n this._userOverlayTimer = this._injectedScript.utils.builtins.setTimeout(tick, 500);\n };\n this._userOverlayTimer = this._injectedScript.utils.builtins.setTimeout(tick, 500);\n }\n _clearUserOverlayTimer() {\n if (this._userOverlayTimer === void 0)\n return;\n this._injectedScript.utils.builtins.clearTimeout(this._userOverlayTimer);\n this._userOverlayTimer = void 0;\n }\n setUserOverlaysVisible(visible) {\n this._userOverlayHidden = !visible;\n this._userOverlayContainer.hidden = !visible || this._userOverlays.size === 0;\n }\n clearHighlight() {\n var _a, _b;\n for (const entry of this._renderedEntries) {\n (_a = entry.highlightElement) == null ? void 0 : _a.remove();\n (_b = entry.tooltipElement) == null ? void 0 : _b.remove();\n }\n this._renderedEntries = [];\n }\n addMaskedElements(elements, color) {\n const existingEntries = this._renderedEntries.map((e) => ({ element: e.targetElement, color: e.color }));\n const newEntries = elements.map((element) => ({ element, color }));\n this.updateHighlight([...existingEntries, ...newEntries]);\n }\n updateHighlight(entries) {\n if (this._highlightIsUpToDate(entries))\n return;\n this.clearHighlight();\n for (const entry of entries) {\n const highlightElement = this._createHighlightElement();\n this._glassPaneShadow.appendChild(highlightElement);\n let tooltipElement;\n if (entry.tooltipText) {\n tooltipElement = this._injectedScript.document.createElement("x-pw-tooltip");\n this._glassPaneShadow.appendChild(tooltipElement);\n tooltipElement.style.top = "0";\n tooltipElement.style.left = "0";\n tooltipElement.style.display = "flex";\n const lineElement = this._injectedScript.document.createElement("x-pw-tooltip-line");\n lineElement.textContent = entry.tooltipText;\n tooltipElement.appendChild(lineElement);\n }\n this._renderedEntries.push({ targetElement: entry.element, box: toDOMRect(entry.box), color: entry.color, cssStyle: entry.cssStyle, tooltipElement, highlightElement });\n }\n for (const entry of this._renderedEntries) {\n if (!entry.box && !entry.targetElement)\n continue;\n entry.box = entry.box || entry.targetElement.getBoundingClientRect();\n if (!entry.tooltipElement)\n continue;\n const { anchorLeft, anchorTop } = this.tooltipPosition(entry.box, entry.tooltipElement);\n entry.tooltipTop = anchorTop;\n entry.tooltipLeft = anchorLeft;\n }\n for (const entry of this._renderedEntries) {\n if (entry.tooltipElement) {\n entry.tooltipElement.style.top = entry.tooltipTop + "px";\n entry.tooltipElement.style.left = entry.tooltipLeft + "px";\n }\n const box = entry.box;\n entry.highlightElement.style.backgroundColor = entry.color;\n entry.highlightElement.style.left = box.x + "px";\n entry.highlightElement.style.top = box.y + "px";\n entry.highlightElement.style.width = box.width + "px";\n entry.highlightElement.style.height = box.height + "px";\n entry.highlightElement.style.display = "block";\n if (entry.cssStyle)\n entry.highlightElement.style.cssText += ";" + entry.cssStyle;\n if (this._isUnderTest)\n console.error("Highlight box for test: " + JSON.stringify({ x: box.x, y: box.y, width: box.width, height: box.height }));\n }\n }\n firstBox() {\n var _a;\n return (_a = this._renderedEntries[0]) == null ? void 0 : _a.box;\n }\n firstTooltipBox() {\n const entry = this._renderedEntries[0];\n if (!entry || !entry.tooltipElement || entry.tooltipLeft === void 0 || entry.tooltipTop === void 0)\n return;\n return {\n x: entry.tooltipLeft,\n y: entry.tooltipTop,\n left: entry.tooltipLeft,\n top: entry.tooltipTop,\n width: entry.tooltipElement.offsetWidth,\n height: entry.tooltipElement.offsetHeight,\n bottom: entry.tooltipTop + entry.tooltipElement.offsetHeight,\n right: entry.tooltipLeft + entry.tooltipElement.offsetWidth,\n toJSON: () => {\n }\n };\n }\n // Note: there is a copy of this method in dialog.tsx. Please fix bugs in both places.\n tooltipPosition(box, tooltipElement) {\n const tooltipWidth = tooltipElement.offsetWidth;\n const tooltipHeight = tooltipElement.offsetHeight;\n const totalWidth = this._glassPaneElement.offsetWidth;\n const totalHeight = this._glassPaneElement.offsetHeight;\n let anchorLeft = Math.max(5, box.left);\n if (anchorLeft + tooltipWidth > totalWidth - 5)\n anchorLeft = totalWidth - tooltipWidth - 5;\n let anchorTop = Math.max(0, box.bottom) + 5;\n if (anchorTop + tooltipHeight > totalHeight - 5) {\n if (Math.max(0, box.top) > tooltipHeight + 5) {\n anchorTop = Math.max(0, box.top) - tooltipHeight - 5;\n } else {\n anchorTop = totalHeight - 5 - tooltipHeight;\n }\n }\n return { anchorLeft, anchorTop };\n }\n _highlightIsUpToDate(entries) {\n if (entries.length !== this._renderedEntries.length)\n return false;\n for (let i = 0; i < this._renderedEntries.length; ++i) {\n if (entries[i].element !== this._renderedEntries[i].targetElement)\n return false;\n if (entries[i].color !== this._renderedEntries[i].color)\n return false;\n if (entries[i].cssStyle !== this._renderedEntries[i].cssStyle)\n return false;\n const oldBox = this._renderedEntries[i].box;\n if (!oldBox)\n return false;\n const box = entries[i].box ? toDOMRect(entries[i].box) : entries[i].element.getBoundingClientRect();\n if (box.top !== oldBox.top || box.right !== oldBox.right || box.bottom !== oldBox.bottom || box.left !== oldBox.left)\n return false;\n }\n return true;\n }\n _createHighlightElement() {\n return this._injectedScript.document.createElement("x-pw-highlight");\n }\n appendChild(element) {\n this._glassPaneShadow.appendChild(element);\n }\n onGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "auto";\n this._glassPaneElement.style.backgroundColor = "rgba(0, 0, 0, 0.3)";\n this._glassPaneElement.addEventListener("click", handler);\n }\n offGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._glassPaneElement.removeEventListener("click", handler);\n }\n};\nfunction cursorPathKeyframes(dx, dy, seed) {\n const random = (salt) => {\n const value = Math.sin(seed * 12.9898 + salt * 78.233) * 43758.5453;\n return value - Math.floor(value);\n };\n const distance = Math.hypot(dx, dy);\n const normalX = -dy / distance;\n const normalY = dx / distance;\n const side = random(1) < 0.5 ? -1 : 1;\n const startBow = side * distance * (0.03 + 0.03 * random(2));\n const endBow = side * distance * (0.01 + 0.02 * random(3));\n const c1x = dx * 2 / 3 + normalX * startBow;\n const c1y = dy * 2 / 3 + normalY * startBow;\n const c2x = dx / 3 + normalX * endBow;\n const c2y = dy / 3 + normalY * endBow;\n const keyframes = [];\n const steps = 30;\n for (let i = 0; i <= steps; i++) {\n const t = i / steps;\n const u = 1 - t;\n const px = u * u * u * dx + 3 * u * u * t * c1x + 3 * u * t * t * c2x;\n const py = u * u * u * dy + 3 * u * u * t * c1y + 3 * u * t * t * c2y;\n keyframes.push({ transform: `translate(${px}px, ${py}px)` });\n }\n return keyframes;\n}\nfunction toDOMRect(box) {\n if (!box)\n return void 0;\n return new DOMRect(box.x, box.y, box.width, box.height);\n}\n\n// packages/injected/src/layoutSelectorUtils.ts\nfunction boxRightOf(box1, box2, maxDistance) {\n const distance = box1.left - box2.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxLeftOf(box1, box2, maxDistance) {\n const distance = box2.left - box1.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxAbove(box1, box2, maxDistance) {\n const distance = box2.top - box1.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxBelow(box1, box2, maxDistance) {\n const distance = box1.top - box2.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxNear(box1, box2, maxDistance) {\n const kThreshold = maxDistance === void 0 ? 50 : maxDistance;\n let score = 0;\n if (box1.left - box2.right >= 0)\n score += box1.left - box2.right;\n if (box2.left - box1.right >= 0)\n score += box2.left - box1.right;\n if (box2.top - box1.bottom >= 0)\n score += box2.top - box1.bottom;\n if (box1.top - box2.bottom >= 0)\n score += box1.top - box2.bottom;\n return score > kThreshold ? void 0 : score;\n}\nvar kLayoutSelectorNames = ["left-of", "right-of", "above", "below", "near"];\nfunction layoutSelectorScore(name, element, inner, maxDistance) {\n const box = element.getBoundingClientRect();\n const scorer = { "left-of": boxLeftOf, "right-of": boxRightOf, "above": boxAbove, "below": boxBelow, "near": boxNear }[name];\n let bestScore;\n for (const e of inner) {\n if (e === element)\n continue;\n const score = scorer(box, e.getBoundingClientRect(), maxDistance);\n if (score === void 0)\n continue;\n if (bestScore === void 0 || score < bestScore)\n bestScore = score;\n }\n return bestScore;\n}\n\n// packages/injected/src/selectorUtils.ts\nfunction matchesAttributePart(value, attr) {\n const objValue = typeof value === "string" && !attr.caseSensitive ? value.toUpperCase() : value;\n const attrValue = typeof attr.value === "string" && !attr.caseSensitive ? attr.value.toUpperCase() : attr.value;\n if (attr.op === "")\n return !!objValue;\n if (attr.op === "=") {\n if (attrValue instanceof RegExp) {\n attrValue.lastIndex = 0;\n return typeof objValue === "string" && !!objValue.match(attrValue);\n }\n return objValue === attrValue;\n }\n if (typeof objValue !== "string" || typeof attrValue !== "string")\n return false;\n if (attr.op === "*=")\n return objValue.includes(attrValue);\n if (attr.op === "^=")\n return objValue.startsWith(attrValue);\n if (attr.op === "$=")\n return objValue.endsWith(attrValue);\n if (attr.op === "|=")\n return objValue === attrValue || objValue.startsWith(attrValue + "-");\n if (attr.op === "~=")\n return objValue.split(" ").includes(attrValue);\n return false;\n}\nfunction shouldSkipForTextMatching(element) {\n const document = element.ownerDocument;\n return element.nodeName === "SCRIPT" || element.nodeName === "NOSCRIPT" || element.nodeName === "STYLE" || document.head && document.head.contains(element);\n}\nfunction elementText(cache, root) {\n let value = cache.get(root);\n if (value === void 0) {\n value = { full: "", normalized: "", immediate: [] };\n if (!shouldSkipForTextMatching(root)) {\n let currentImmediate = "";\n if (root instanceof HTMLInputElement && (root.type === "submit" || root.type === "button" || root.type === "reset")) {\n value = { full: root.value, normalized: normalizeWhiteSpace(root.value), immediate: [root.value] };\n } else {\n for (let child = root.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.TEXT_NODE) {\n value.full += child.nodeValue || "";\n currentImmediate += child.nodeValue || "";\n } else if (child.nodeType === Node.COMMENT_NODE) {\n continue;\n } else {\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n currentImmediate = "";\n if (child.nodeType === Node.ELEMENT_NODE)\n value.full += elementText(cache, child).full;\n }\n }\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n if (root.shadowRoot)\n value.full += elementText(cache, root.shadowRoot).full;\n if (value.full)\n value.normalized = normalizeWhiteSpace(value.full);\n }\n }\n cache.set(root, value);\n }\n return value;\n}\nfunction elementMatchesText(cache, element, matcher) {\n if (shouldSkipForTextMatching(element))\n return "none";\n if (!matcher(elementText(cache, element)))\n return "none";\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.ELEMENT_NODE && matcher(elementText(cache, child)))\n return "selfAndChildren";\n }\n if (element.shadowRoot && matcher(elementText(cache, element.shadowRoot)))\n return "selfAndChildren";\n return "self";\n}\nfunction getElementLabels(textCache, element, options) {\n let labels = getAriaLabelledByElements(element);\n if (labels) {\n if (options == null ? void 0 : options.skipRefsInsideElement)\n labels = labels.filter((label) => label !== element && !element.contains(label));\n return labels.map((label) => elementText(textCache, label));\n }\n const ariaLabel = element.getAttribute("aria-label");\n if (ariaLabel !== null && !!ariaLabel.trim())\n return [{ full: ariaLabel, normalized: normalizeWhiteSpace(ariaLabel), immediate: [ariaLabel] }];\n const isNonHiddenInput = element.nodeName === "INPUT" && element.type !== "hidden";\n if (["BUTTON", "METER", "OUTPUT", "PROGRESS", "SELECT", "TEXTAREA"].includes(element.nodeName) || isNonHiddenInput) {\n const labels2 = element.labels;\n if (labels2)\n return [...labels2].map((label) => elementText(textCache, label));\n }\n return [];\n}\n\n// packages/injected/src/roleSelectorEngine.ts\nvar kSupportedAttributes = ["selected", "checked", "pressed", "expanded", "level", "disabled", "name", "description", "include-hidden"];\nkSupportedAttributes.sort();\nfunction validateSupportedRole(attr, roles, role) {\n if (!roles.includes(role))\n throw new Error(`"${attr}" attribute is only supported for roles: ${roles.slice().sort().map((role2) => `"${role2}"`).join(", ")}`);\n}\nfunction validateSupportedValues(attr, values) {\n if (attr.op !== "" && !values.includes(attr.value))\n throw new Error(`"${attr.name}" must be one of ${values.map((v) => JSON.stringify(v)).join(", ")}`);\n}\nfunction validateSupportedOp(attr, ops) {\n if (!ops.includes(attr.op))\n throw new Error(`"${attr.name}" does not support "${attr.op}" matcher`);\n}\nfunction validateAttributes(attrs, role) {\n const options = { role };\n for (const attr of attrs) {\n switch (attr.name) {\n case "checked": {\n validateSupportedRole(attr.name, kAriaCheckedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.checked = attr.op === "" ? true : attr.value;\n break;\n }\n case "pressed": {\n validateSupportedRole(attr.name, kAriaPressedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.pressed = attr.op === "" ? true : attr.value;\n break;\n }\n case "selected": {\n validateSupportedRole(attr.name, kAriaSelectedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.selected = attr.op === "" ? true : attr.value;\n break;\n }\n case "expanded": {\n validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.expanded = attr.op === "" ? true : attr.value;\n break;\n }\n case "level": {\n validateSupportedRole(attr.name, kAriaLevelRoles, role);\n if (typeof attr.value === "string")\n attr.value = +attr.value;\n if (attr.op !== "=" || typeof attr.value !== "number" || Number.isNaN(attr.value))\n throw new Error(`"level" attribute must be compared to a number`);\n options.level = attr.value;\n break;\n }\n case "disabled": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.disabled = attr.op === "" ? true : attr.value;\n break;\n }\n case "name": {\n if (attr.op === "")\n throw new Error(`"name" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"name" attribute must be a string or a regular expression`);\n options.name = attr.value;\n options.nameOp = attr.op;\n options.nameExact = attr.caseSensitive;\n break;\n }\n case "description": {\n if (attr.op === "")\n throw new Error(`"description" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"description" attribute must be a string or a regular expression`);\n options.description = attr.value;\n options.descriptionOp = attr.op;\n options.descriptionExact = attr.caseSensitive;\n break;\n }\n case "include-hidden": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.includeHidden = attr.op === "" ? true : attr.value;\n break;\n }\n default: {\n throw new Error(`Unknown attribute "${attr.name}", must be one of ${kSupportedAttributes.map((a) => `"${a}"`).join(", ")}.`);\n }\n }\n }\n return options;\n}\nfunction queryRole(scope, options, internal) {\n const result = [];\n const match = (element) => {\n if (getAriaRole(element) !== options.role)\n return;\n if (options.selected !== void 0 && getAriaSelected(element) !== options.selected)\n return;\n if (options.checked !== void 0 && getAriaChecked(element) !== options.checked)\n return;\n if (options.pressed !== void 0 && getAriaPressed(element) !== options.pressed)\n return;\n if (options.expanded !== void 0 && getAriaExpanded(element) !== options.expanded)\n return;\n if (options.level !== void 0 && getAriaLevel(element) !== options.level)\n return;\n if (options.disabled !== void 0 && getAriaDisabled(element) !== options.disabled)\n return;\n if (!options.includeHidden) {\n const isHidden = isElementHiddenForAria(element);\n if (isHidden)\n return;\n }\n if (options.name !== void 0) {\n const accessibleName = normalizeWhiteSpace(getElementAccessibleNameText(element, !!options.includeHidden));\n if (typeof options.name === "string")\n options.name = normalizeWhiteSpace(options.name);\n if (internal && !options.nameExact && options.nameOp === "=")\n options.nameOp = "*=";\n if (!matchesAttributePart(accessibleName, { name: "", jsonPath: [], op: options.nameOp || "=", value: options.name, caseSensitive: !!options.nameExact }))\n return;\n }\n if (options.description !== void 0) {\n const accessibleDescription = normalizeWhiteSpace(getElementAccessibleDescription(element, !!options.includeHidden).text);\n if (typeof options.description === "string")\n options.description = normalizeWhiteSpace(options.description);\n if (internal && !options.descriptionExact && options.descriptionOp === "=")\n options.descriptionOp = "*=";\n if (!matchesAttributePart(accessibleDescription, { name: "", jsonPath: [], op: options.descriptionOp || "=", value: options.description, caseSensitive: !!options.descriptionExact }))\n return;\n }\n result.push(element);\n };\n const query = (root) => {\n const shadows = [];\n if (root.shadowRoot)\n shadows.push(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n match(element);\n if (element.shadowRoot)\n shadows.push(element.shadowRoot);\n }\n shadows.forEach(query);\n };\n query(scope);\n return result;\n}\nfunction createRoleEngine(internal) {\n return {\n queryAll: (scope, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n const role = parsed.name.toLowerCase();\n if (!role)\n throw new Error(`Role must not be empty`);\n const options = validateAttributes(parsed.attributes, role);\n beginAriaCaches();\n try {\n return queryRole(scope, options, internal);\n } finally {\n endAriaCaches();\n }\n }\n };\n}\n\n// packages/injected/src/selectorEvaluator.ts\nvar SelectorEvaluatorImpl = class {\n constructor() {\n this._retainCacheCounter = 0;\n this._cacheText = /* @__PURE__ */ new Map();\n this._cacheQueryCSS = /* @__PURE__ */ new Map();\n this._cacheMatches = /* @__PURE__ */ new Map();\n this._cacheQuery = /* @__PURE__ */ new Map();\n this._cacheMatchesSimple = /* @__PURE__ */ new Map();\n this._cacheMatchesParents = /* @__PURE__ */ new Map();\n this._cacheCallMatches = /* @__PURE__ */ new Map();\n this._cacheCallQuery = /* @__PURE__ */ new Map();\n this._cacheQuerySimple = /* @__PURE__ */ new Map();\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("not", notEngine);\n this._engines.set("is", isEngine);\n this._engines.set("where", isEngine);\n this._engines.set("has", hasEngine);\n this._engines.set("scope", scopeEngine);\n this._engines.set("light", lightEngine);\n this._engines.set("visible", visibleEngine);\n this._engines.set("text", textEngine);\n this._engines.set("text-is", textIsEngine);\n this._engines.set("text-matches", textMatchesEngine);\n this._engines.set("has-text", hasTextEngine);\n this._engines.set("right-of", createLayoutEngine("right-of"));\n this._engines.set("left-of", createLayoutEngine("left-of"));\n this._engines.set("above", createLayoutEngine("above"));\n this._engines.set("below", createLayoutEngine("below"));\n this._engines.set("near", createLayoutEngine("near"));\n this._engines.set("nth-match", nthMatchEngine);\n const allNames = [...this._engines.keys()];\n allNames.sort();\n const parserNames = [...customCSSNames];\n parserNames.sort();\n if (allNames.join("|") !== parserNames.join("|"))\n throw new Error(`Please keep customCSSNames in sync with evaluator engines: ${allNames.join("|")} vs ${parserNames.join("|")}`);\n }\n begin() {\n ++this._retainCacheCounter;\n }\n end() {\n --this._retainCacheCounter;\n if (!this._retainCacheCounter) {\n this._cacheQueryCSS.clear();\n this._cacheMatches.clear();\n this._cacheQuery.clear();\n this._cacheMatchesSimple.clear();\n this._cacheMatchesParents.clear();\n this._cacheCallMatches.clear();\n this._cacheCallQuery.clear();\n this._cacheQuerySimple.clear();\n this._cacheText.clear();\n }\n }\n _cached(cache, main, rest, cb) {\n if (!cache.has(main))\n cache.set(main, []);\n const entries = cache.get(main);\n const entry = entries.find((e) => rest.every((value, index) => e.rest[index] === value));\n if (entry)\n return entry.result;\n const result = cb();\n entries.push({ rest, result });\n return result;\n }\n _checkSelector(s) {\n const wellFormed = typeof s === "object" && s && (Array.isArray(s) || "simples" in s && s.simples.length);\n if (!wellFormed)\n throw new Error(`Malformed selector "${s}"`);\n return s;\n }\n matches(element, s, context) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheMatches, element, [selector, context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._matchesEngine(isEngine, element, selector, context);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n if (!this._matchesSimple(element, selector.simples[selector.simples.length - 1].selector, context))\n return false;\n return this._matchesParents(element, selector, selector.simples.length - 2, context);\n });\n } finally {\n this.end();\n }\n }\n query(context, s) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheQuery, selector, [context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._queryEngine(isEngine, context, selector);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n const previousScoreMap = this._scoreMap;\n this._scoreMap = /* @__PURE__ */ new Map();\n let elements = this._querySimple(context, selector.simples[selector.simples.length - 1].selector);\n elements = elements.filter((element) => this._matchesParents(element, selector, selector.simples.length - 2, context));\n if (this._scoreMap.size) {\n elements.sort((a, b) => {\n const aScore = this._scoreMap.get(a);\n const bScore = this._scoreMap.get(b);\n if (aScore === bScore)\n return 0;\n if (aScore === void 0)\n return 1;\n if (bScore === void 0)\n return -1;\n return aScore - bScore;\n });\n }\n this._scoreMap = previousScoreMap;\n return elements;\n });\n } finally {\n this.end();\n }\n }\n _markScore(element, score) {\n if (this._scoreMap)\n this._scoreMap.set(element, score);\n }\n _hasScopeClause(selector) {\n return selector.simples.some((simple) => simple.selector.functions.some((f) => f.name === "scope"));\n }\n _expandContextForScopeMatching(context) {\n if (context.scope.nodeType !== 1)\n return context;\n const scope = parentElementOrShadowHost(context.scope);\n if (!scope)\n return context;\n return { ...context, scope, originalScope: context.originalScope || context.scope };\n }\n _matchesSimple(element, simple, context) {\n return this._cached(this._cacheMatchesSimple, element, [simple, context.scope, context.pierceShadow, context.originalScope], () => {\n if (element === context.scope)\n return false;\n if (simple.css && !this._matchesCSS(element, simple.css))\n return false;\n for (const func of simple.functions) {\n if (!this._matchesEngine(this._getEngine(func.name), element, func.args, context))\n return false;\n }\n return true;\n });\n }\n _querySimple(context, simple) {\n if (!simple.functions.length)\n return this._queryCSS(context, simple.css || "*");\n return this._cached(this._cacheQuerySimple, simple, [context.scope, context.pierceShadow, context.originalScope], () => {\n let css = simple.css;\n const funcs = simple.functions;\n if (css === "*" && funcs.length)\n css = void 0;\n let elements;\n let firstIndex = -1;\n if (css !== void 0) {\n elements = this._queryCSS(context, css);\n } else {\n firstIndex = funcs.findIndex((func) => this._getEngine(func.name).query !== void 0);\n if (firstIndex === -1)\n firstIndex = 0;\n elements = this._queryEngine(this._getEngine(funcs[firstIndex].name), context, funcs[firstIndex].args);\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches !== void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches === void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n return elements;\n });\n }\n _matchesParents(element, complex, index, context) {\n if (index < 0)\n return true;\n return this._cached(this._cacheMatchesParents, element, [complex, index, context.scope, context.pierceShadow, context.originalScope], () => {\n const { selector: simple, combinator } = complex.simples[index];\n if (combinator === ">") {\n const parent = parentElementOrShadowHostInContext(element, context);\n if (!parent || !this._matchesSimple(parent, simple, context))\n return false;\n return this._matchesParents(parent, complex, index - 1, context);\n }\n if (combinator === "+") {\n const previousSibling = previousSiblingInContext(element, context);\n if (!previousSibling || !this._matchesSimple(previousSibling, simple, context))\n return false;\n return this._matchesParents(previousSibling, complex, index - 1, context);\n }\n if (combinator === "") {\n let parent = parentElementOrShadowHostInContext(element, context);\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n if (combinator === "~") {\n let previousSibling = previousSiblingInContext(element, context);\n while (previousSibling) {\n if (this._matchesSimple(previousSibling, simple, context)) {\n if (this._matchesParents(previousSibling, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "~")\n break;\n }\n previousSibling = previousSiblingInContext(previousSibling, context);\n }\n return false;\n }\n if (combinator === ">=") {\n let parent = element;\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n throw new Error(`Unsupported combinator "${combinator}"`);\n });\n }\n _matchesEngine(engine, element, args, context) {\n if (engine.matches)\n return this._callMatches(engine, element, args, context);\n if (engine.query)\n return this._callQuery(engine, args, context).includes(element);\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _queryEngine(engine, context, args) {\n if (engine.query)\n return this._callQuery(engine, args, context);\n if (engine.matches)\n return this._queryCSS(context, "*").filter((element) => this._callMatches(engine, element, args, context));\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _callMatches(engine, element, args, context) {\n return this._cached(this._cacheCallMatches, element, [engine, context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.matches(element, args, context, this);\n });\n }\n _callQuery(engine, args, context) {\n return this._cached(this._cacheCallQuery, engine, [context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.query(context, args, this);\n });\n }\n _matchesCSS(element, css) {\n return element.matches(css);\n }\n _queryCSS(context, css) {\n return this._cached(this._cacheQueryCSS, css, [context.scope, context.pierceShadow, context.originalScope], () => {\n let result = [];\n function query(root) {\n result = result.concat([...root.querySelectorAll(css)]);\n if (!context.pierceShadow)\n return;\n if (root.shadowRoot)\n query(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n if (element.shadowRoot)\n query(element.shadowRoot);\n }\n }\n query(context.scope);\n return result;\n });\n }\n _getEngine(name) {\n const engine = this._engines.get(name);\n if (!engine)\n throw new Error(`Unknown selector engine "${name}"`);\n return engine;\n }\n};\nvar isEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n return args.some((selector) => evaluator.matches(element, selector, context));\n },\n query(context, args, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n let elements = [];\n for (const arg of args)\n elements = elements.concat(evaluator.query(context, arg));\n return args.length === 1 ? elements : sortInDOMOrder(elements);\n }\n};\nvar hasEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"has" engine expects non-empty selector list`);\n return evaluator.query({ ...context, scope: element }, args).length > 0;\n }\n // TODO: we can implement efficient "query" by matching "args" and returning\n // all parents/descendants, just have to be careful with the ":scope" matching.\n};\nvar scopeEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9)\n return element === actualScope.documentElement;\n return element === actualScope;\n },\n query(context, args, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9) {\n const root = actualScope.documentElement;\n return root ? [root] : [];\n }\n if (actualScope.nodeType === 1)\n return [actualScope];\n return [];\n }\n};\nvar notEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"not" engine expects non-empty selector list`);\n return !evaluator.matches(element, args, context);\n }\n};\nvar lightEngine = {\n query(context, args, evaluator) {\n return evaluator.query({ ...context, pierceShadow: false }, args);\n },\n matches(element, args, context, evaluator) {\n return evaluator.matches(element, args, { ...context, pierceShadow: false });\n }\n};\nvar visibleEngine = {\n matches(element, args, context, evaluator) {\n if (args.length)\n throw new Error(`"visible" engine expects no arguments`);\n return isElementVisible(element);\n }\n};\nvar textEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar textIsEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text-is" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]);\n const matcher = (elementText2) => {\n if (!text && !elementText2.immediate.length)\n return true;\n return elementText2.immediate.some((s) => normalizeWhiteSpace(s) === text);\n };\n return elementMatchesText(evaluator._cacheText, element, matcher) !== "none";\n }\n};\nvar textMatchesEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0 || typeof args[0] !== "string" || args.length > 2 || args.length === 2 && typeof args[1] !== "string")\n throw new Error(`"text-matches" engine expects a regexp body and optional regexp flags`);\n const re = new RegExp(args[0], args.length === 2 ? args[1] : void 0);\n const matcher = (elementText2) => {\n re.lastIndex = 0;\n return re.test(elementText2.full);\n };\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar hasTextEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"has-text" engine expects a single string`);\n if (shouldSkipForTextMatching(element))\n return false;\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return matcher(elementText(evaluator._cacheText, element));\n }\n};\nfunction createLayoutEngine(name) {\n return {\n matches(element, args, context, evaluator) {\n const maxDistance = args.length && typeof args[args.length - 1] === "number" ? args[args.length - 1] : void 0;\n const queryArgs = maxDistance === void 0 ? args : args.slice(0, args.length - 1);\n if (args.length < 1 + (maxDistance === void 0 ? 0 : 1))\n throw new Error(`"${name}" engine expects a selector list and optional maximum distance in pixels`);\n const inner = evaluator.query(context, queryArgs);\n const score = layoutSelectorScore(name, element, inner, maxDistance);\n if (score === void 0)\n return false;\n evaluator._markScore(element, score);\n return true;\n }\n };\n}\nvar nthMatchEngine = {\n query(context, args, evaluator) {\n let index = args[args.length - 1];\n if (args.length < 2)\n throw new Error(`"nth-match" engine expects non-empty selector list and an index argument`);\n if (typeof index !== "number" || index < 1)\n throw new Error(`"nth-match" engine expects a one-based index as the last argument`);\n const elements = isEngine.query(context, args.slice(0, args.length - 1), evaluator);\n index--;\n return index < elements.length ? [elements[index]] : [];\n }\n};\nfunction parentElementOrShadowHostInContext(element, context) {\n if (element === context.scope)\n return;\n if (!context.pierceShadow)\n return element.parentElement || void 0;\n return parentElementOrShadowHost(element);\n}\nfunction previousSiblingInContext(element, context) {\n if (element === context.scope)\n return;\n return element.previousElementSibling || void 0;\n}\nfunction sortInDOMOrder(elements) {\n const elementToEntry = /* @__PURE__ */ new Map();\n const roots = [];\n const result = [];\n function append(element) {\n let entry = elementToEntry.get(element);\n if (entry)\n return entry;\n const parent = parentElementOrShadowHost(element);\n if (parent) {\n const parentEntry = append(parent);\n parentEntry.children.push(element);\n } else {\n roots.push(element);\n }\n entry = { children: [], taken: false };\n elementToEntry.set(element, entry);\n return entry;\n }\n for (const e of elements)\n append(e).taken = true;\n function visit(element) {\n const entry = elementToEntry.get(element);\n if (entry.taken)\n result.push(element);\n if (entry.children.length > 1) {\n const set = new Set(entry.children);\n entry.children = [];\n let child = element.firstElementChild;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n child = element.shadowRoot ? element.shadowRoot.firstElementChild : null;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n }\n entry.children.forEach(visit);\n }\n roots.forEach(visit);\n return result;\n}\n\n// packages/injected/src/selectorGenerator.ts\nvar kTextScoreRange = 10;\nvar kExactPenalty = kTextScoreRange / 2;\nvar kTestIdScore = 1;\nvar kOtherTestIdScore = 2;\nvar kIframeByAttributeScore = 10;\nvar kBeginPenalizedScore = 50;\nvar kRoleWithNameScore = 100;\nvar kPlaceholderScore = 120;\nvar kLabelScore = 140;\nvar kAltTextScore = 160;\nvar kTextScore = 180;\nvar kTitleScore = 200;\nvar kTextScoreRegex = 250;\nvar kPlaceholderScoreExact = kPlaceholderScore + kExactPenalty;\nvar kLabelScoreExact = kLabelScore + kExactPenalty;\nvar kRoleWithNameScoreExact = kRoleWithNameScore + kExactPenalty;\nvar kAltTextScoreExact = kAltTextScore + kExactPenalty;\nvar kTextScoreExact = kTextScore + kExactPenalty;\nvar kTitleScoreExact = kTitleScore + kExactPenalty;\nvar kEndPenalizedScore = 300;\nvar kCSSIdScore = 500;\nvar kRoleWithoutNameScore = 510;\nvar kCSSInputTypeNameScore = 520;\nvar kCSSTagNameScore = 530;\nvar kNthScore = 1e4;\nvar kCSSFallbackScore = 1e7;\nvar kScoreThresholdForTextExpect = 1e3;\nfunction generateSelector(injectedScript, targetElement, options) {\n var _a;\n injectedScript._evaluator.begin();\n const cache = { allowText: /* @__PURE__ */ new Map(), disallowText: /* @__PURE__ */ new Map() };\n beginAriaCaches();\n beginDOMCaches();\n try {\n let targetTokens;\n if (options.forTextExpect) {\n targetTokens = cssFallback(injectedScript, targetElement.ownerDocument.documentElement, options);\n for (let element = targetElement; element; element = parentElementOrShadowHost(element)) {\n const tokens = generateSelectorFor(cache, injectedScript, element, { ...options, noText: true });\n if (!tokens)\n continue;\n const score = combineScores(tokens);\n if (score <= kScoreThresholdForTextExpect) {\n targetTokens = tokens;\n break;\n }\n }\n } else {\n if (!targetElement.matches("input,textarea,select") && !targetElement.isContentEditable) {\n const interactiveParent = closestCrossShadow(targetElement, "button,select,input,[role=button],[role=checkbox],[role=radio],a,[role=link]", options.root);\n if (interactiveParent && isElementVisible(interactiveParent))\n targetElement = interactiveParent;\n }\n targetTokens = generateSelectorFor(cache, injectedScript, targetElement, options) || cssFallback(injectedScript, targetElement, options);\n }\n const selector = joinTokens(targetTokens);\n const parsedSelector = injectedScript.parseSelector(selector);\n return {\n selector,\n elements: injectedScript.querySelectorAll(parsedSelector, (_a = options.root) != null ? _a : targetElement.ownerDocument)\n };\n } finally {\n endDOMCaches();\n endAriaCaches();\n injectedScript._evaluator.end();\n }\n}\nfunction generateSelectorFor(cache, injectedScript, targetElement, options) {\n var _a;\n if (options.root && !isInsideScope(options.root, targetElement))\n throw new Error(`Target element must belong to the root\'s subtree`);\n if (targetElement === options.root)\n return [{ engine: "css", selector: ":scope", score: 1 }];\n if (targetElement.ownerDocument.documentElement === targetElement)\n return [{ engine: "css", selector: "html", score: 1 }];\n let result = null;\n const updateResult = (candidate) => {\n if (!result || combineScores(candidate) < combineScores(result))\n result = candidate;\n };\n const candidates = [];\n for (const candidate of buildTextCandidates(injectedScript, targetElement, !options.isRecursive, options))\n candidates.push({ candidate, isTextCandidate: true });\n for (const token of buildNoTextCandidates(injectedScript, targetElement, options)) {\n if (options.omitInternalEngines && token.engine.startsWith("internal:"))\n continue;\n candidates.push({ candidate: [token], isTextCandidate: false });\n }\n candidates.sort((a, b) => combineScores(a.candidate) - combineScores(b.candidate));\n for (const { candidate, isTextCandidate } of candidates) {\n const elements = injectedScript.querySelectorAll(injectedScript.parseSelector(joinTokens(candidate)), (_a = options.root) != null ? _a : targetElement.ownerDocument);\n if (!elements.includes(targetElement)) {\n continue;\n }\n if (elements.length === 1) {\n updateResult(candidate);\n break;\n }\n const index = elements.indexOf(targetElement);\n if (index > 5) {\n continue;\n }\n updateResult([...candidate, { engine: "nth", selector: String(index), score: kNthScore }]);\n if (options.isRecursive) {\n continue;\n }\n for (let parent = parentElementOrShadowHost(targetElement); parent && parent !== options.root; parent = parentElementOrShadowHost(parent)) {\n const filtered = elements.filter((e) => isInsideScope(parent, e) && e !== parent);\n const newIndex = filtered.indexOf(targetElement);\n if (filtered.length > 5 || newIndex === -1 || newIndex === index && filtered.length > 1) {\n continue;\n }\n const inParent = filtered.length === 1 ? candidate : [...candidate, { engine: "nth", selector: String(newIndex), score: kNthScore }];\n const idealSelectorForParent = { engine: "", selector: "", score: 1 };\n if (result && combineScores([idealSelectorForParent, ...inParent]) >= combineScores(result)) {\n continue;\n }\n const noText = !!options.noText || isTextCandidate;\n const cacheMap = noText ? cache.disallowText : cache.allowText;\n let parentTokens = cacheMap.get(parent);\n if (parentTokens === void 0) {\n parentTokens = generateSelectorFor(cache, injectedScript, parent, { ...options, isRecursive: true, noText }) || cssFallback(injectedScript, parent, options);\n cacheMap.set(parent, parentTokens);\n }\n if (!parentTokens)\n continue;\n updateResult([...parentTokens, ...inParent]);\n }\n }\n return result;\n}\nfunction buildNoTextCandidates(injectedScript, element, options) {\n const candidates = [];\n const testIdAttributeNames = splitTestIdAttributeNames(options.testIdAttributeName);\n {\n for (const attr of ["data-testid", "data-test-id", "data-test"]) {\n if (!testIdAttributeNames.includes(attr) && element.getAttribute(attr))\n candidates.push({ engine: "css", selector: `[${attr}=${quoteCSSAttributeValue(element.getAttribute(attr))}]`, score: kOtherTestIdScore });\n }\n const idAttr = element.getAttribute("id");\n if (idAttr && !isGuidLike(idAttr))\n candidates.push({ engine: "css", selector: makeSelectorForId(idAttr), score: kCSSIdScore });\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore });\n }\n if (element.nodeName === "IFRAME" || element.nodeName === "FRAME") {\n for (const attribute of ["name", "title"]) {\n if (element.getAttribute(attribute))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[${attribute}=${quoteCSSAttributeValue(element.getAttribute(attribute))}]`, score: kIframeByAttributeScore });\n }\n for (const testIdAttr of testIdAttributeNames) {\n if (element.getAttribute(testIdAttr))\n candidates.push({ engine: "css", selector: `[${testIdAttr}=${quoteCSSAttributeValue(element.getAttribute(testIdAttr))}]`, score: kTestIdScore });\n }\n penalizeScoreForLength([candidates]);\n return candidates;\n }\n for (const testIdAttr of testIdAttributeNames) {\n if (element.getAttribute(testIdAttr))\n candidates.push({ engine: "internal:testid", selector: `[${testIdAttr}=${escapeForAttributeSelector(element.getAttribute(testIdAttr), true)}]`, score: kTestIdScore });\n }\n if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") {\n const input = element;\n if (input.placeholder) {\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(input.placeholder, true)}]`, score: kPlaceholderScoreExact });\n for (const alternative of suitableTextAlternatives(input.placeholder))\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(alternative.text, false)}]`, score: kPlaceholderScore - alternative.scoreBonus });\n }\n }\n const labels = getElementLabels(injectedScript._evaluator._cacheText, element, { skipRefsInsideElement: options.noText });\n for (const label of labels) {\n const labelText = label.normalized;\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(labelText, true), score: kLabelScoreExact });\n for (const alternative of suitableTextAlternatives(labelText))\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(alternative.text, false), score: kLabelScore - alternative.scoreBonus });\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole))\n candidates.push({ engine: "internal:role", selector: ariaRole, score: kRoleWithoutNameScore });\n if (element.getAttribute("name") && ["BUTTON", "FORM", "FIELDSET", "FRAME", "IFRAME", "INPUT", "KEYGEN", "OBJECT", "OUTPUT", "SELECT", "TEXTAREA", "MAP", "META", "PARAM"].includes(element.nodeName))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[name=${quoteCSSAttributeValue(element.getAttribute("name"))}]`, score: kCSSInputTypeNameScore });\n if (["INPUT", "TEXTAREA"].includes(element.nodeName) && element.getAttribute("type") !== "hidden") {\n if (element.getAttribute("type"))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[type=${quoteCSSAttributeValue(element.getAttribute("type"))}]`, score: kCSSInputTypeNameScore });\n }\n if (["INPUT", "TEXTAREA", "SELECT"].includes(element.nodeName) && element.getAttribute("type") !== "hidden")\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSInputTypeNameScore + 1 });\n penalizeScoreForLength([candidates]);\n return candidates;\n}\nfunction buildTextCandidates(injectedScript, element, isTargetNode, options) {\n if (element.nodeName === "SELECT")\n return [];\n const candidates = [];\n if (!options.noText) {\n const title = element.getAttribute("title");\n if (title) {\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(title, true)}]`, score: kTitleScoreExact }]);\n for (const alternative of suitableTextAlternatives(title))\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(alternative.text, false)}]`, score: kTitleScore - alternative.scoreBonus }]);\n }\n const alt = element.getAttribute("alt");\n if (alt && ["APPLET", "AREA", "IMG", "INPUT"].includes(element.nodeName)) {\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alt, true)}]`, score: kAltTextScoreExact }]);\n for (const alternative of suitableTextAlternatives(alt))\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alternative.text, false)}]`, score: kAltTextScore - alternative.scoreBonus }]);\n }\n }\n const text = options.noText ? "" : elementText(injectedScript._evaluator._cacheText, element).normalized;\n const textAlternatives = text ? suitableTextAlternatives(text) : [];\n if (text) {\n if (isTargetNode) {\n if (text.length <= 80)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(text, true), score: kTextScoreExact }]);\n for (const alternative of textAlternatives)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n }\n const cssToken = { engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore };\n for (const alternative of textAlternatives)\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (isTargetNode && text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole)) {\n const accessibleName = getElementAccessibleName(element, false);\n const ariaName = options.noText && accessibleName.derivedFromContent ? "" : accessibleName.text;\n const accessibleDescription = getElementAccessibleDescription(element, false);\n const ariaDescription = options.noText && accessibleDescription.derivedFromContent ? "" : accessibleDescription.text;\n if (ariaName && !ariaName.match(/^\\p{Co}+$/u)) {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}]`, score: kRoleWithNameScoreExact };\n candidates.push([roleToken]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}]`, score: kRoleWithNameScore - alternative.scoreBonus }]);\n if (ariaDescription) {\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}][description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithNameScoreExact + 1 }]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}][description=${escapeForAttributeSelector(ariaDescription, false)}]`, score: kRoleWithNameScore - alternative.scoreBonus + 1 }]);\n }\n } else {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}`, score: kRoleWithoutNameScore };\n if (ariaDescription)\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithoutNameScore + 1 }]);\n for (const alternative of textAlternatives)\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (!options.noText && isTargetNode && text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n }\n penalizeScoreForLength(candidates);\n return candidates;\n}\nfunction makeSelectorForId(id) {\n return /^[a-zA-Z][a-zA-Z0-9\\-\\_]+$/.test(id) ? "#" + id : `[id=${quoteCSSAttributeValue(id)}]`;\n}\nfunction cssFallback(injectedScript, targetElement, options) {\n var _a;\n const root = (_a = options.root) != null ? _a : targetElement.ownerDocument;\n const tokens = [];\n function uniqueCSSSelector(prefix) {\n const path = tokens.slice();\n if (prefix)\n path.unshift(prefix);\n const selector = path.join(" > ");\n const parsedSelector = injectedScript.parseSelector(selector);\n const node = injectedScript.querySelector(parsedSelector, root, false);\n return node === targetElement ? selector : void 0;\n }\n function makeStrict(selector) {\n const token = { engine: "css", selector, score: kCSSFallbackScore };\n const parsedSelector = injectedScript.parseSelector(selector);\n const elements = injectedScript.querySelectorAll(parsedSelector, root);\n if (elements.length === 1)\n return [token];\n const nth = { engine: "nth", selector: String(elements.indexOf(targetElement)), score: kNthScore };\n return [token, nth];\n }\n for (let element = targetElement; element && element !== root; element = parentElementOrShadowHost(element)) {\n let bestTokenForLevel = "";\n if (element.id) {\n const token = makeSelectorForId(element.id);\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n bestTokenForLevel = token;\n }\n const parent = element.parentNode;\n const classes = [...element.classList].map(escapeClassName);\n for (let i = 0; i < classes.length; ++i) {\n const token = "." + classes.slice(0, i + 1).join(".");\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel && parent) {\n const sameClassSiblings = parent.querySelectorAll(token);\n if (sameClassSiblings.length === 1)\n bestTokenForLevel = token;\n }\n }\n if (parent) {\n const siblings = [...parent.children];\n const nodeName = element.nodeName;\n const sameTagSiblings = siblings.filter((sibling) => sibling.nodeName === nodeName);\n const token = sameTagSiblings.indexOf(element) === 0 ? escapeNodeName(element) : `${escapeNodeName(element)}:nth-child(${1 + siblings.indexOf(element)})`;\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel)\n bestTokenForLevel = token;\n } else if (!bestTokenForLevel) {\n bestTokenForLevel = escapeNodeName(element);\n }\n tokens.unshift(bestTokenForLevel);\n }\n return makeStrict(uniqueCSSSelector());\n}\nfunction penalizeScoreForLength(groups) {\n for (const group of groups) {\n for (const token of group) {\n if (token.score > kBeginPenalizedScore && token.score < kEndPenalizedScore)\n token.score += Math.min(kTextScoreRange, token.selector.length / 10 | 0);\n }\n }\n}\nfunction joinTokens(tokens) {\n const parts = [];\n let lastEngine = "";\n for (const { engine, selector } of tokens) {\n if (parts.length && (lastEngine !== "css" || engine !== "css" || selector.startsWith(":nth-match(")))\n parts.push(">>");\n lastEngine = engine;\n if (engine === "css")\n parts.push(selector);\n else\n parts.push(`${engine}=${selector}`);\n }\n return parts.join(" ");\n}\nfunction combineScores(tokens) {\n let score = 0;\n for (let i = 0; i < tokens.length; i++)\n score += tokens[i].score * (tokens.length - i);\n return score;\n}\nfunction isGuidLike(id) {\n let lastCharacterType;\n let transitionCount = 0;\n for (let i = 0; i < id.length; ++i) {\n const c = id[i];\n let characterType;\n if (c === "-" || c === "_")\n continue;\n if (c >= "a" && c <= "z")\n characterType = "lower";\n else if (c >= "A" && c <= "Z")\n characterType = "upper";\n else if (c >= "0" && c <= "9")\n characterType = "digit";\n else\n characterType = "other";\n if (characterType === "lower" && lastCharacterType === "upper") {\n lastCharacterType = characterType;\n continue;\n }\n if (lastCharacterType && lastCharacterType !== characterType)\n ++transitionCount;\n lastCharacterType = characterType;\n }\n return transitionCount >= id.length / 4;\n}\nfunction trimWordBoundary(text, maxLength) {\n if (text.length <= maxLength)\n return text;\n text = text.substring(0, maxLength);\n const match = text.match(/^(.*)\\b(.+?)$/);\n if (!match)\n return "";\n return match[1].trimEnd();\n}\nfunction suitableTextAlternatives(text) {\n let result = [];\n {\n const match = text.match(/^([\\d.,]+)[^.,\\w]/);\n const leadingNumberLength = match ? match[1].length : 0;\n if (leadingNumberLength) {\n const alt = trimWordBoundary(text.substring(leadingNumberLength).trimStart(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n {\n const match = text.match(/[^.,\\w]([\\d.,]+)$/);\n const trailingNumberLength = match ? match[1].length : 0;\n if (trailingNumberLength) {\n const alt = trimWordBoundary(text.substring(0, text.length - trailingNumberLength).trimEnd(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n if (text.length <= 30) {\n result.push({ text, scoreBonus: 0 });\n } else {\n result.push({ text: trimWordBoundary(text, 80), scoreBonus: 0 });\n result.push({ text: trimWordBoundary(text, 30), scoreBonus: 1 });\n }\n result = result.filter((r) => r.text);\n if (!result.length)\n result.push({ text: text.substring(0, 80), scoreBonus: 0 });\n return result;\n}\nfunction escapeNodeName(node) {\n return node.nodeName.toLocaleLowerCase().replace(/[:\\.]/g, (char) => "\\\\" + char);\n}\nfunction escapeClassName(className) {\n let result = "";\n for (let i = 0; i < className.length; i++)\n result += cssEscapeCharacter(className, i);\n return result;\n}\nfunction cssEscapeCharacter(s, i) {\n const c = s.charCodeAt(i);\n if (c === 0)\n return "\\uFFFD";\n if (c >= 1 && c <= 31 || c >= 48 && c <= 57 && (i === 0 || i === 1 && s.charCodeAt(0) === 45))\n return "\\\\" + c.toString(16) + " ";\n if (i === 0 && c === 45 && s.length === 1)\n return "\\\\" + s.charAt(i);\n if (c >= 128 || c === 45 || c === 95 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122)\n return s.charAt(i);\n return "\\\\" + s.charAt(i);\n}\n\n// packages/injected/src/xpathSelectorEngine.ts\nvar XPathEngine = {\n queryAll(root, selector) {\n if (selector.startsWith("/") && root.nodeType !== Node.DOCUMENT_NODE)\n selector = "." + selector;\n const result = [];\n const document = root.ownerDocument || root;\n if (!document)\n return result;\n const it = document.evaluate(selector, root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);\n for (let node = it.iterateNext(); node; node = it.iterateNext()) {\n if (node.nodeType === Node.ELEMENT_NODE)\n result.push(node);\n }\n return result;\n }\n};\n\n// packages/injected/src/consoleApi.ts\nvar selectorSymbol = /* @__PURE__ */ Symbol("selector");\nselectorSymbol;\nvar _Locator = class _Locator {\n constructor(injectedScript, selector, options) {\n if (options == null ? void 0 : options.hasText)\n selector += ` >> internal:has-text=${escapeForTextSelector(options.hasText, false)}`;\n if (options == null ? void 0 : options.hasNotText)\n selector += ` >> internal:has-not-text=${escapeForTextSelector(options.hasNotText, false)}`;\n if (options == null ? void 0 : options.has)\n selector += ` >> internal:has=` + JSON.stringify(options.has[selectorSymbol]);\n if (options == null ? void 0 : options.hasNot)\n selector += ` >> internal:has-not=` + JSON.stringify(options.hasNot[selectorSymbol]);\n if ((options == null ? void 0 : options.visible) !== void 0)\n selector += ` >> visible=${options.visible ? "true" : "false"}`;\n this[selectorSymbol] = selector;\n if (selector) {\n const parsed = injectedScript.parseSelector(selector);\n this.element = injectedScript.querySelector(parsed, injectedScript.document, false);\n this.elements = injectedScript.querySelectorAll(parsed, injectedScript.document);\n }\n const selectorBase = selector;\n const self = this;\n self.locator = (selector2, options2) => {\n return new _Locator(injectedScript, selectorBase ? selectorBase + " >> " + selector2 : selector2, options2);\n };\n self.getByTestId = (testId) => self.locator(getByTestIdSelector(injectedScript.testIdAttributeNameForStrictErrorAndConsoleCodegen(), testId));\n self.getByAltText = (text, options2) => self.locator(getByAltTextSelector(text, options2));\n self.getByLabel = (text, options2) => self.locator(getByLabelSelector(text, options2));\n self.getByPlaceholder = (text, options2) => self.locator(getByPlaceholderSelector(text, options2));\n self.getByText = (text, options2) => self.locator(getByTextSelector(text, options2));\n self.getByTitle = (text, options2) => self.locator(getByTitleSelector(text, options2));\n self.getByRole = (role, options2 = {}) => self.locator(getByRoleSelector(role, options2));\n self.filter = (options2) => new _Locator(injectedScript, selector, options2);\n self.visible = () => new _Locator(injectedScript, selector, { visible: true });\n self.first = () => self.locator("nth=0");\n self.last = () => self.locator("nth=-1");\n self.nth = (index) => self.locator(`nth=${index}`);\n self.and = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:and=` + JSON.stringify(locator[selectorSymbol]));\n self.or = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:or=` + JSON.stringify(locator[selectorSymbol]));\n }\n};\nvar Locator = _Locator;\nvar ConsoleAPI = class {\n constructor(injectedScript) {\n this._injectedScript = injectedScript;\n }\n install() {\n if (this._injectedScript.window.playwright)\n return;\n this._injectedScript.window.playwright = {\n $: (selector, strict) => this._querySelector(selector, !!strict),\n $$: (selector) => this._querySelectorAll(selector),\n inspect: (selector) => this._inspect(selector),\n selector: (element) => this._selector(element),\n generateLocator: (element, language) => this._generateLocator(element, language),\n ariaSnapshot: (element, options) => {\n return this._injectedScript.ariaSnapshot(element || this._injectedScript.document.body, options || { mode: "default" });\n },\n resume: () => this._resume(),\n ...new Locator(this._injectedScript, "")\n };\n delete this._injectedScript.window.playwright.filter;\n delete this._injectedScript.window.playwright.visible;\n delete this._injectedScript.window.playwright.first;\n delete this._injectedScript.window.playwright.last;\n delete this._injectedScript.window.playwright.nth;\n delete this._injectedScript.window.playwright.and;\n delete this._injectedScript.window.playwright.or;\n }\n _querySelector(selector, strict) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.query(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelector(parsed, this._injectedScript.document, strict);\n }\n _querySelectorAll(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.$$(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelectorAll(parsed, this._injectedScript.document);\n }\n _inspect(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.inspect(\'Playwright >> selector\').`);\n this._injectedScript.window.inspect(this._querySelector(selector, false));\n }\n _selector(element) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.selector(element).`);\n return this._injectedScript.generateSelectorSimple(element);\n }\n _generateLocator(element, language) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.locator(element).`);\n const selector = this._injectedScript.generateSelectorSimple(element);\n return asLocator(language || "javascript", selector);\n }\n _resume() {\n if (!this._injectedScript.window.__pw_resume)\n return false;\n this._injectedScript.window.__pw_resume().catch(() => {\n });\n }\n};\n\n// packages/isomorphic/utilityScriptSerializers.ts\nvar kFunctionBindingPrefix = "__pw_fn_";\nvar kBindingsControllerProperty = "__playwright__binding__controller__";\nfunction isRegExp2(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\n } catch (error) {\n return false;\n }\n}\nfunction isMap(obj) {\n try {\n return obj instanceof Map || Object.prototype.toString.call(obj) === "[object Map]";\n } catch (error) {\n return false;\n }\n}\nfunction isSet(obj) {\n try {\n return obj instanceof Set || Object.prototype.toString.call(obj) === "[object Set]";\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("m" in value) {\n const result = /* @__PURE__ */ new Map();\n refs.set(value.id, result);\n for (const { k, v } of value.m)\n result.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs));\n return result;\n }\n if ("s" in value) {\n const result = /* @__PURE__ */ new Set();\n refs.set(value.id, result);\n for (const item of value.s)\n result.add(parseEvaluationResultValue(item, handles, refs));\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("fn" in value) {\n const name = value.fn;\n return (...args) => globalThis[kBindingsControllerProperty].callBinding(name, ...args);\n }\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer, options = {}) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0, extendedSerialization: options.extendedSerialization });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp2(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (visitorInfo.extendedSerialization) {\n if (isMap(value)) {\n const m = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.entries();\n const next = (/* @__PURE__ */ new Map()).entries().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) });\n }\n return { m, id: id2 };\n }\n if (isSet(value)) {\n const s = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.values();\n const next = (/* @__PURE__ */ new Set()).values().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n s.push(serialize(entry.value, handleSerializer, visitorInfo));\n }\n return { s, id: id2 };\n }\n }\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n if (typeof value === "function" && value.name.startsWith(kFunctionBindingPrefix))\n return { fn: value.name };\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date,\n AbortSignal: global.AbortSignal,\n Temporal: global.Temporal\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n return returnByValue ? this._promiseAwareJsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _promiseAwareJsonValueNoThrow(value) {\n const safeJson = (value2) => {\n try {\n return this.jsonValue(true, value2);\n } catch (e) {\n return void 0;\n }\n };\n if (value && typeof value === "object" && typeof value.then === "function") {\n return (async () => {\n const promiseValue = await value;\n return safeJson(promiseValue);\n })();\n }\n return safeJson(value);\n }\n};\n\n// packages/injected/src/injectedScript.ts\nvar InjectedScript = class {\n constructor(window, options) {\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = "data-testid";\n // Recorder must use any external dependencies through InjectedScript.\n // Otherwise it will end up with a copy of all modules it uses, and any\n // module-level globals will be duplicated, which leads to subtle bugs.\n this.utils = {\n asLocator,\n cacheNormalizedWhitespaces,\n elementText,\n getAriaRole,\n getElementAccessibleNameText,\n getElementAccessibleDescription,\n isElementVisible,\n isInsideScope,\n normalizeWhiteSpace,\n parseAriaSnapshot,\n generateAriaTree,\n findNewElement,\n // Builtins protect injected code from clock emulation.\n builtins: null\n };\n this.window = window;\n this.document = window.document;\n this.isUnderTest = options.isUnderTest;\n this.utils.builtins = new UtilityScript(window, options.isUnderTest).builtins;\n this._sdkLanguage = options.sdkLanguage;\n this._frameSeq = options.frameSeq;\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = options.testIdAttributeName;\n this._evaluator = new SelectorEvaluatorImpl();\n this.consoleApi = new ConsoleAPI(this);\n this.onGlobalListenersRemoved = /* @__PURE__ */ new Set();\n this._autoClosingTags = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]);\n this._booleanAttributes = /* @__PURE__ */ new Set(["checked", "selected", "disabled", "readonly", "multiple"]);\n this._eventTypes = /* @__PURE__ */ new Map([\n ["auxclick", "mouse"],\n ["click", "mouse"],\n ["dblclick", "mouse"],\n ["mousedown", "mouse"],\n ["mouseeenter", "mouse"],\n ["mouseleave", "mouse"],\n ["mousemove", "mouse"],\n ["mouseout", "mouse"],\n ["mouseover", "mouse"],\n ["mouseup", "mouse"],\n ["mouseleave", "mouse"],\n ["mousewheel", "mouse"],\n ["keydown", "keyboard"],\n ["keyup", "keyboard"],\n ["keypress", "keyboard"],\n ["textInput", "keyboard"],\n ["touchstart", "touch"],\n ["touchmove", "touch"],\n ["touchend", "touch"],\n ["touchcancel", "touch"],\n ["pointerover", "pointer"],\n ["pointerout", "pointer"],\n ["pointerenter", "pointer"],\n ["pointerleave", "pointer"],\n ["pointerdown", "pointer"],\n ["pointerup", "pointer"],\n ["pointermove", "pointer"],\n ["pointercancel", "pointer"],\n ["gotpointercapture", "pointer"],\n ["lostpointercapture", "pointer"],\n ["focus", "focus"],\n ["blur", "focus"],\n ["drag", "drag"],\n ["dragstart", "drag"],\n ["dragend", "drag"],\n ["dragover", "drag"],\n ["dragenter", "drag"],\n ["dragleave", "drag"],\n ["dragexit", "drag"],\n ["drop", "drag"],\n ["wheel", "wheel"],\n ["deviceorientation", "deviceorientation"],\n ["deviceorientationabsolute", "deviceorientation"],\n ["devicemotion", "devicemotion"]\n ]);\n this._hoverHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousemove"]);\n this._tapHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["pointerdown", "pointerup", "touchstart", "touchend", "touchcancel"]);\n this._mouseHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousedown", "mouseup", "pointerdown", "pointerup", "click", "auxclick", "dblclick", "contextmenu"]);\n this._allHitTargetInterceptorEvents = /* @__PURE__ */ new Set([...this._hoverHitTargetInterceptorEvents, ...this._tapHitTargetInterceptorEvents, ...this._mouseHitTargetInterceptorEvents]);\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("xpath", XPathEngine);\n this._engines.set("xpath:light", XPathEngine);\n this._engines.set("role", createRoleEngine(false));\n this._engines.set("text", this._createTextEngine(true, false));\n this._engines.set("text:light", this._createTextEngine(false, false));\n this._engines.set("id", this._createAttributeEngine("id", true));\n this._engines.set("id:light", this._createAttributeEngine("id", false));\n this._engines.set("data-testid", this._createAttributeEngine("data-testid", true));\n this._engines.set("data-testid:light", this._createAttributeEngine("data-testid", false));\n this._engines.set("data-test-id", this._createAttributeEngine("data-test-id", true));\n this._engines.set("data-test-id:light", this._createAttributeEngine("data-test-id", false));\n this._engines.set("data-test", this._createAttributeEngine("data-test", true));\n this._engines.set("data-test:light", this._createAttributeEngine("data-test", false));\n this._engines.set("css", this._createCSSEngine());\n this._engines.set("nth", { queryAll: () => [] });\n this._engines.set("visible", this._createVisibleEngine());\n this._engines.set("internal:control", this._createControlEngine());\n this._engines.set("internal:has", this._createHasEngine());\n this._engines.set("internal:has-not", this._createHasNotEngine());\n this._engines.set("internal:and", { queryAll: () => [] });\n this._engines.set("internal:or", { queryAll: () => [] });\n this._engines.set("internal:chain", this._createInternalChainEngine());\n this._engines.set("internal:label", this._createInternalLabelEngine());\n this._engines.set("internal:text", this._createTextEngine(true, true));\n this._engines.set("internal:has-text", this._createInternalHasTextEngine());\n this._engines.set("internal:has-not-text", this._createInternalHasNotTextEngine());\n this._engines.set("internal:attr", this._createNamedAttributeEngine());\n this._engines.set("internal:testid", this._createTestIdEngine());\n this._engines.set("internal:role", createRoleEngine(true));\n this._engines.set("internal:describe", this._createDescribeEngine());\n this._engines.set("aria-ref", this._createAriaRefEngine());\n this._engines.set("aria-template", this._createAriaTemplateEngine());\n for (const { name, source } of options.customEngines)\n this._engines.set(name, this.eval(source));\n this._stableRafCount = options.stableRafCount;\n this._browserName = options.browserName;\n this._shouldPrependErrorPrefix = !!options.shouldPrependErrorPrefix;\n this._isUtilityWorld = !!options.isUtilityWorld;\n setGlobalOptions({ browserNameForWorkarounds: options.browserName });\n this._setupGlobalListenersRemovalDetection();\n this._setupHitTargetInterceptors();\n if (this.isUnderTest)\n this.window.__injectedScript = this;\n }\n eval(expression) {\n return this.window.eval(expression);\n }\n testIdAttributeNameForStrictErrorAndConsoleCodegen() {\n return this._testIdAttributeNameForStrictErrorAndConsoleCodegen;\n }\n parseSelector(selector) {\n const result = parseSelector(selector);\n visitAllSelectorParts(result, (part) => {\n if (!this._engines.has(part.name))\n throw this.createStacklessError(`Unknown engine "${part.name}" while parsing selector ${selector}`);\n });\n return result;\n }\n generateSelector(targetElement, options) {\n return generateSelector(this, targetElement, options);\n }\n generateSelectorSimple(targetElement, options) {\n return generateSelector(this, targetElement, { ...options, testIdAttributeName: this._testIdAttributeNameForStrictErrorAndConsoleCodegen }).selector;\n }\n querySelector(selector, root, strict) {\n const result = this.querySelectorAll(selector, root);\n if (strict && result.length > 1)\n throw this.strictModeViolationError(selector, result);\n this.checkDeprecatedSelectorUsage(selector, result);\n return result[0];\n }\n _queryNth(elements, part) {\n const list = [...elements];\n let nth = +part.body;\n if (nth === -1)\n nth = list.length - 1;\n return new Set(list.slice(nth, nth + 1));\n }\n _queryLayoutSelector(elements, part, originalRoot) {\n const name = part.name;\n const body = part.body;\n const result = [];\n const inner = this.querySelectorAll(body.parsed, originalRoot);\n for (const element of elements) {\n const score = layoutSelectorScore(name, element, inner, body.distance);\n if (score !== void 0)\n result.push({ element, score });\n }\n result.sort((a, b) => a.score - b.score);\n return new Set(result.map((r) => r.element));\n }\n ariaSnapshot(node, options) {\n const { json } = this.ariaSnapshotJSON(node, options);\n return renderAriaSnapshotAsYaml(json, { convertStringsToRegex: options.mode === "codegen" });\n }\n ariaSnapshotJSON(node, options) {\n if (node.nodeType !== Node.ELEMENT_NODE)\n throw this.createStacklessError("Can only capture aria snapshot of Element nodes.");\n options = { ...options, refPrefix: this._frameSeq && options.mode === "ai" ? "f" + this._frameSeq : "" };\n const ariaSnapshot = generateAriaTree(node, options);\n const rendered = renderAriaTreeAsJSON(ariaSnapshot, options);\n this._lastAriaSnapshotForQuery = ariaSnapshot;\n return { json: rendered.json, iframeRefs: ariaSnapshot.iframeRefs, iframeDepths: rendered.iframeDepths };\n }\n ariaSnapshotForRecorder() {\n const tree = generateAriaTree(this.document.body, { mode: "ai" });\n const { json } = renderAriaTreeAsJSON(tree, { mode: "ai" });\n return { ariaSnapshot: renderAriaSnapshotAsYaml(json), refs: tree.refs };\n }\n ariaSnapshotForExpectFailure(element, options) {\n const { json } = renderAriaTreeAsJSON(generateAriaTree(element, options), options);\n return renderAriaSnapshotAsYaml(json);\n }\n documentContent(includeShadow) {\n let content = "";\n if (this.document.doctype)\n content = new XMLSerializer().serializeToString(this.document.doctype);\n const root = this.document.documentElement;\n if (!root)\n return content;\n if (!includeShadow)\n return content + root.outerHTML;\n const shadowRoots = [];\n const collectShadowRoots = (node) => {\n for (const element of node.querySelectorAll("*")) {\n if (element.shadowRoot) {\n shadowRoots.push(element.shadowRoot);\n collectShadowRoots(element.shadowRoot);\n }\n }\n };\n collectShadowRoots(this.document);\n const emptyRoot = root.cloneNode(false).outerHTML;\n const endTagIndex = emptyRoot.lastIndexOf(" part.name === "nth"))\n throw this.createStacklessError(`Can\'t query n-th element in a request with the capture.`);\n const withHas = { parts: selector.parts.slice(0, selector.capture + 1) };\n if (selector.capture < selector.parts.length - 1) {\n const parsed = { parts: selector.parts.slice(selector.capture + 1) };\n const has = { name: "internal:has", body: { parsed }, source: stringifySelector(parsed) };\n withHas.parts.push(has);\n }\n return this.querySelectorAll(withHas, root);\n }\n if (!root["querySelectorAll"])\n throw this.createStacklessError("Node is not queryable.");\n if (selector.capture !== void 0) {\n throw this.createStacklessError("Internal error: there should not be a capture in the selector.");\n }\n if (root.nodeType === 11 && selector.parts.length === 1 && selector.parts[0].name === "css" && selector.parts[0].source === ":scope")\n return [root];\n this._evaluator.begin();\n try {\n let roots = /* @__PURE__ */ new Set([root]);\n for (const part of selector.parts) {\n if (part.name === "nth") {\n roots = this._queryNth(roots, part);\n } else if (part.name === "internal:and") {\n const andElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(andElements.filter((e) => roots.has(e)));\n } else if (part.name === "internal:or") {\n const orElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(sortInDOMOrder(/* @__PURE__ */ new Set([...roots, ...orElements])));\n } else if (kLayoutSelectorNames.includes(part.name)) {\n roots = this._queryLayoutSelector(roots, part, root);\n } else {\n const next = /* @__PURE__ */ new Set();\n for (const root2 of roots) {\n const all = this._queryEngineAll(part, root2);\n for (const one of all)\n next.add(one);\n }\n roots = next;\n }\n }\n return [...roots];\n } finally {\n this._evaluator.end();\n }\n }\n _queryEngineAll(part, root) {\n const result = this._engines.get(part.name).queryAll(root, part.body);\n for (const element of result) {\n if (!("nodeName" in element))\n throw this.createStacklessError(`Expected a Node but got ${Object.prototype.toString.call(element)}`);\n }\n return result;\n }\n _createAttributeEngine(attribute, shadow) {\n const toCSS = (selector) => {\n const css = `[${attribute}=${JSON.stringify(selector)}]`;\n return [{ simples: [{ selector: { css, functions: [] }, combinator: "" }] }];\n };\n return {\n queryAll: (root, selector) => {\n return this._evaluator.query({ scope: root, pierceShadow: shadow }, toCSS(selector));\n }\n };\n }\n _createCSSEngine() {\n return {\n queryAll: (root, body) => {\n return this._evaluator.query({ scope: root, pierceShadow: true }, body);\n }\n };\n }\n _createTextEngine(shadow, internal) {\n const queryAll = (root, selector) => {\n const { matcher, kind } = createTextMatcher(selector, internal);\n const result = [];\n let lastDidNotMatchSelf = null;\n const appendElement = (element) => {\n if (kind === "lax" && lastDidNotMatchSelf && lastDidNotMatchSelf.contains(element))\n return false;\n const matches = elementMatchesText(this._evaluator._cacheText, element, matcher);\n if (matches === "none")\n lastDidNotMatchSelf = element;\n if (matches === "self" || matches === "selfAndChildren" && kind === "strict" && !internal)\n result.push(element);\n };\n if (root.nodeType === Node.ELEMENT_NODE)\n appendElement(root);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: shadow }, "*");\n for (const element of elements)\n appendElement(element);\n return result;\n };\n return { queryAll };\n }\n _createInternalHasTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [element] : [];\n }\n };\n }\n _createInternalHasNotTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [] : [element];\n }\n };\n }\n _createInternalLabelEngine() {\n return {\n queryAll: (root, selector) => {\n const { matcher } = createTextMatcher(selector, true);\n const allElements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, "*");\n return allElements.filter((element) => {\n return getElementLabels(this._evaluator._cacheText, element).some((label) => matcher(label));\n });\n }\n };\n }\n _createNamedAttributeEngine() {\n const queryAll = (root, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n if (parsed.name || parsed.attributes.length !== 1)\n throw new Error("Malformed attribute selector: " + selector);\n const { name } = parsed.attributes[0];\n const matcher = createAttributeMatcher(parsed.attributes[0]);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, `[${name}]`);\n return elements.filter((e) => matcher(e.getAttribute(name)));\n };\n return { queryAll };\n }\n _createTestIdEngine() {\n const queryAll = (root, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n if (parsed.name || parsed.attributes.length !== 1)\n throw new Error("Malformed test id selector: " + selector);\n const names = splitTestIdAttributeNames(parsed.attributes[0].name);\n const matcher = createAttributeMatcher(parsed.attributes[0]);\n const cssQuery = names.map((n) => `[${n}]`).join(",");\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, cssQuery);\n return elements.filter((e) => names.some((n) => {\n const actual = e.getAttribute(n);\n return actual !== null && matcher(actual);\n }));\n };\n return { queryAll };\n }\n _createDescribeEngine() {\n const queryAll = (root) => {\n if (root.nodeType !== 1)\n return [];\n return [root];\n };\n return { queryAll };\n }\n _createControlEngine() {\n return {\n queryAll(root, body) {\n if (body === "enter-frame")\n return [];\n if (body === "any-frame")\n return [];\n if (body === "return-empty")\n return [];\n if (body === "component") {\n if (root.nodeType !== 1)\n return [];\n return [root.childElementCount === 1 ? root.firstElementChild : root];\n }\n throw new Error(`Internal error, unknown internal:control selector ${body}`);\n }\n };\n }\n _createHasEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [root] : [];\n };\n return { queryAll };\n }\n _createHasNotEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [] : [root];\n };\n return { queryAll };\n }\n _createVisibleEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const visible = body === "true";\n return isElementVisible(root) === visible ? [root] : [];\n };\n return { queryAll };\n }\n _createInternalChainEngine() {\n const queryAll = (root, body) => {\n return this.querySelectorAll(body.parsed, root);\n };\n return { queryAll };\n }\n extend(source, params) {\n const constrFunction = this.window.eval(`\n (() => {\n const module = {};\n ${source}\n return module.exports.default();\n })()`);\n return new constrFunction(this, params);\n }\n async viewportRatio(element) {\n return await new Promise((resolve) => {\n const observer = new IntersectionObserver((entries) => {\n resolve(entries[0].intersectionRatio);\n observer.disconnect();\n });\n observer.observe(element);\n this.utils.builtins.requestAnimationFrame(() => {\n });\n });\n }\n getElementBorderWidth(node) {\n if (node.nodeType !== Node.ELEMENT_NODE || !node.ownerDocument || !node.ownerDocument.defaultView)\n return { left: 0, top: 0 };\n const style = node.ownerDocument.defaultView.getComputedStyle(node);\n return { left: parseInt(style.borderLeftWidth || "", 10), top: parseInt(style.borderTopWidth || "", 10) };\n }\n describeIFrameStyle(iframe) {\n if (!iframe.ownerDocument || !iframe.ownerDocument.defaultView)\n return "error:notconnected";\n const defaultView = iframe.ownerDocument.defaultView;\n for (let e = iframe; e; e = parentElementOrShadowHost(e)) {\n if (defaultView.getComputedStyle(e).transform !== "none")\n return "transformed";\n }\n const iframeStyle = defaultView.getComputedStyle(iframe);\n return {\n left: parseInt(iframeStyle.borderLeftWidth || "", 10) + parseInt(iframeStyle.paddingLeft || "", 10),\n top: parseInt(iframeStyle.borderTopWidth || "", 10) + parseInt(iframeStyle.paddingTop || "", 10)\n };\n }\n retarget(node, behavior) {\n let element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;\n if (!element)\n return null;\n if (behavior === "none")\n return element;\n if (!element.matches("input, textarea, select") && !element.isContentEditable) {\n if (behavior === "button-link")\n element = element.closest("button, [role=button], a, [role=link]") || element;\n else\n element = element.closest("button, [role=button], [role=checkbox], [role=radio]") || element;\n }\n if (behavior === "follow-label") {\n if (!element.matches("a, input, textarea, button, select, [role=link], [role=button], [role=checkbox], [role=radio]") && !element.isContentEditable) {\n const enclosingLabel = element.closest("label");\n if (enclosingLabel && enclosingLabel.control)\n element = enclosingLabel.control;\n }\n }\n return element;\n }\n async checkElementStates(node, states, frameVisible) {\n if (states.includes("stable")) {\n const stableResult = await this._checkElementIsStable(node);\n if (stableResult === false)\n return { missingState: "stable" };\n if (stableResult === "error:notconnected")\n return "error:notconnected";\n }\n for (const state of states) {\n if (state !== "stable") {\n const result = this.elementState(node, state, frameVisible);\n if (result.received === "error:notconnected")\n return "error:notconnected";\n if (!result.matches)\n return { missingState: state };\n }\n }\n }\n async _checkElementIsStable(node) {\n const continuePolling = /* @__PURE__ */ Symbol("continuePolling");\n let lastRect;\n let stableRafCounter = 0;\n let lastTime = 0;\n const check = () => {\n const element = this.retarget(node, "no-follow-label");\n if (!element)\n return "error:notconnected";\n const time = this.utils.builtins.performance.now();\n if (this._stableRafCount > 1 && time - lastTime < 15)\n return continuePolling;\n lastTime = time;\n const clientRect = element.getBoundingClientRect();\n const rect = { x: clientRect.top, y: clientRect.left, width: clientRect.width, height: clientRect.height };\n if (lastRect) {\n const samePosition = rect.x === lastRect.x && rect.y === lastRect.y && rect.width === lastRect.width && rect.height === lastRect.height;\n if (!samePosition)\n return false;\n if (++stableRafCounter >= this._stableRafCount)\n return true;\n }\n lastRect = rect;\n return continuePolling;\n };\n let fulfill;\n let reject;\n const result = new Promise((f, r) => {\n fulfill = f;\n reject = r;\n });\n const raf = () => {\n try {\n const success = check();\n if (success !== continuePolling)\n fulfill(success);\n else\n this.utils.builtins.requestAnimationFrame(raf);\n } catch (e) {\n reject(e);\n }\n };\n this.utils.builtins.requestAnimationFrame(raf);\n return result;\n }\n _createAriaRefEngine() {\n const queryAll = (root, selector) => {\n var _a, _b;\n const result = (_b = (_a = this._lastAriaSnapshotForQuery) == null ? void 0 : _a.info) == null ? void 0 : _b.get(selector);\n return result && result.element.isConnected ? [result.element] : [];\n };\n return { queryAll };\n }\n _createAriaTemplateEngine() {\n const queryAll = (root, body) => {\n const template = JSON.parse(body);\n const rootElement = root.nodeType === 9 ? root.documentElement : root;\n if (!rootElement)\n return [];\n return getAllElementsMatchingExpectAriaTemplate(rootElement, template);\n };\n return { queryAll };\n }\n elementState(node, state, frameVisible) {\n const element = this.retarget(node, ["visible", "hidden"].includes(state) ? "none" : "follow-label");\n if (!element || !element.isConnected) {\n if (state === "hidden")\n return { matches: true, received: "hidden" };\n return { matches: false, received: "error:notconnected" };\n }\n if (state === "visible" || state === "hidden") {\n const visible = !!frameVisible && isElementVisible(element);\n return {\n matches: state === "visible" ? visible : !visible,\n received: visible ? "visible" : "hidden"\n };\n }\n if (state === "disabled" || state === "enabled") {\n const disabled = getAriaDisabled(element);\n return {\n matches: state === "disabled" ? disabled : !disabled,\n received: disabled ? "disabled" : "enabled"\n };\n }\n if (state === "editable") {\n const disabled = getAriaDisabled(element);\n const readonly = getReadonly(element);\n if (readonly === "error")\n throw this.createStacklessError("Element is not an

` : ""; + const styleSheet = ` + @keyframes pw-chapter-fade-in { + from { opacity: 0; } + to { opacity: 1; } + } + @keyframes pw-chapter-fade-out { + from { opacity: 1; } + to { opacity: 0; } + } + #background { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + backdrop-filter: blur(2px); + animation: pw-chapter-fade-in ${fadeDuration}ms ease-out forwards; + } + #background.fade-out { + animation: pw-chapter-fade-out ${fadeDuration}ms ease-in forwards; + } + #content { + background: rgba(0, 0, 0, 0.7); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 16px; + padding: 40px 56px; + max-width: 560px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + } + #title { + color: white; + font-family: system-ui, -apple-system, sans-serif; + font-size: 28px; + font-weight: 600; + line-height: 1.3; + text-align: center; + letter-spacing: -0.01em; + } + #description { + color: rgba(255, 255, 255, 0.7); + font-family: system-ui, -apple-system, sans-serif; + font-size: 15px; + line-height: 1.5; + margin-top: 12px; + text-align: center; + } + `; + const duration = options.duration ?? 2e3; + const html = `
${escapeHTML(options.title)}
${descriptionHtml}
`; + const id = await this.show(html); + await new Promise((f) => setTimeout(f, duration)); + const utility = await this._page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, id: id2, fadeDuration: fadeDuration2 }) => { + const overlay = injected.getUserOverlay(id2); + const bg = overlay?.querySelector("#background"); + if (bg) + bg.classList.add("fade-out"); + return new Promise((f) => injected.utils.builtins.setTimeout(f, fadeDuration2)); + }, { injected: await utility.injectedScript(), id, fadeDuration }).catch((e) => debugLogger.log("error", e)); + await this.remove(id); + } + async setVisible(visible2) { + if (!this._overlays.size) + return; + const utility = await this._page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, visible: visible3 }) => { + injected.setUserOverlaysVisible(visible3); + }, { injected: await utility.injectedScript(), visible: visible2 }).catch((e) => debugLogger.log("error", e)); + } + }; + } +}); + +// packages/playwright-core/src/server/screencast.ts +var Screencast; +var init_screencast = __esm({ + "packages/playwright-core/src/server/screencast.ts"() { + "use strict"; + init_manualPromise(); + init_protocolFormatter(); + init_debugLogger(); + init_page(); + init_progress(); + init_dom(); + Screencast = class { + constructor(page) { + this._clients = /* @__PURE__ */ new Map(); + this.page = page; + this.page.instrumentation.addListener(this, this.page.browserContext); + this.page.on(Page.Events.InternalFrameNavigatedToNewDocument, (frame) => { + if (!frame.parentFrame() && this._cursorPoint) + this._restoreCursor(this._cursorPoint).catch((e) => debugLogger.log("error", e)); + }); + } + async handlePageOrContextClose() { + const clients = [...this._clients.keys()]; + for (const scope of this._clients.values()) + scope.reject(new Error("Screencast closed")); + this._clients.clear(); + for (const client of clients) { + if (client.gracefulClose) + await client.gracefulClose(); + } + } + dispose() { + for (const scope of this._clients.values()) + scope.reject(new Error("Screencast disposed")); + for (const client of this._clients.keys()) + client.dispose(); + this._clients.clear(); + this.page.instrumentation.removeListener(this); + } + showActions(options) { + const title = options.fontSize !== void 0 ? `font-size: ${options.fontSize}px; ${options.style?.title ?? ""}` : options.style?.title; + this._actions = { ...options, style: { ...options.style, title } }; + if (options.cursor === "none") + this._hideCursor(); + } + hideActions() { + this._actions = void 0; + this._hideCursor(); + } + async _restoreCursor(point) { + const utility = await this.page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, point: point2 }) => injected.restoreScreencastCursor(point2), { injected: await utility.injectedScript(), point }); + } + _hideCursor() { + if (!this._cursorPoint) + return; + this._cursorPoint = void 0; + const frame = this.page.mainFrame(); + frame.raceAgainstEvaluationStallingEvents(async () => { + const injectedScript = await frame.existingContext("utility")?.injectedScript(); + await injectedScript?.evaluate((injected) => injected.hideScreencastCursor()); + }).catch((e) => debugLogger.log("error", e)); + } + addClient(client) { + const isFirst = this._clients.size === 0; + this._clients.set(client, new LongStandingScope()); + if (isFirst) { + this._startScreencast(client.size, client.quality, client.fps); + } else if (this._lastFrame) { + const frame = this._lastFrame; + setTimeout(() => { + if (this._clients.has(client)) + void client.onFrame(frame); + }, 0); + } + return { size: this._size }; + } + removeClient(client) { + const scope = this._clients.get(client); + if (!scope) + return; + this._clients.delete(client); + scope.reject(new Error("Screencast client removed")); + if (!this._clients.size) + this._stopScreencast(); + } + _startScreencast(size, quality, fps) { + this._size = size; + if (!this._size) { + const viewport = this.page.browserContext._options.viewport || { width: 800, height: 600 }; + const scale = Math.min(1, 800 / Math.max(viewport.width, viewport.height)); + this._size = { + width: Math.floor(viewport.width * scale), + height: Math.floor(viewport.height * scale) + }; + } + this._size = { + width: this._size.width & ~1, + height: this._size.height & ~1 + }; + this.page.delegate.startScreencast({ + width: this._size.width, + height: this._size.height, + quality: quality ?? 90, + fps + }); + } + _stopScreencast() { + this._lastFrame = void 0; + this.page.delegate.stopScreencast(); + } + async onScreencastFrame(frame) { + this._lastFrame = frame; + let syncAck = false; + const asyncResults = []; + for (const [client, scope] of this._clients) { + const result2 = client.onFrame(frame); + if (result2) + asyncResults.push(scope.safeRace(result2.catch(() => { + }))); + else + syncAck = true; + } + if (!syncAck && asyncResults.length) + await Promise.race(asyncResults); + } + async onBeforeInputAction(progress2, sdkObject, point, box) { + if (!this._actions) + return; + const page = sdkObject.attribution.page; + if (page !== this.page) + return; + if (!box && this._actions.style?.highlight && sdkObject instanceof ElementHandle) + box = await sdkObject.boundingBox(nullProgress) || void 0; + const actionTitle2 = renderFullTitleForCall(progress2.metadata, this.page.browserContext._browser.sdkLanguage()); + const cursor = this._actions?.cursor ?? "pointer"; + const lastCursorPoint = this._cursorPoint; + if (point && cursor !== "none") + this._cursorPoint = point; + const utility = await progress2.race(page.mainFrame().utilityContext()); + const injected = await progress2.race(utility.injectedScript()); + await progress2.race(utility.evaluate(async (options) => { + const { injected: injected2, duration } = options; + injected2.setScreencastAnnotation(options); + await new Promise((f) => injected2.utils.builtins.setTimeout(f, duration)); + injected2.setScreencastAnnotation(null); + }, { + injected, + duration: this._actions?.duration ?? 500, + point, + box, + actionTitle: actionTitle2, + position: this._actions?.position, + cursor, + style: this._actions?.style, + lastCursorPoint + }).catch((e) => debugLogger.log("error", e))); + } + }; + } +}); + +// packages/playwright-core/src/server/page.ts +async function ariaSnapshotJSONForFrame(progress2, frame, selector, options = {}) { + const snapshot3 = await frame.retryWithProgressAndTimeouts(progress2, [1e3, 2e3, 4e3, 8e3], async (progress3, continuePolling) => { + try { + const resolved = await progress3.race(frame.selectors.callOnSelector({ selector: selector || "body,frameset", strict: options.strict ?? !!selector }, ({ injected, elements }, ariaOptions) => { + return injected.ariaSnapshotJSON(elements[0], ariaOptions); + }, { + mode: options.mode ?? "default", + doNotRenderActive: options.doNotRenderActive, + depth: options.depth, + boxes: options.boxes + })); + if (!resolved) { + if (selector) + throw new NonRecoverableDOMError(`Selector "${selector}" does not match any element`); + return continuePolling; + } + return { ...resolved.result, resolvedFrame: resolved.frame }; + } catch (e) { + if (frame.isNonRetriableError(e)) + throw e; + return continuePolling; + } + }); + const renderedIframeRefs = snapshot3.iframeRefs.filter((ref) => ref in snapshot3.iframeDepths); + progress2.setAllowConcurrentOrNestedRaces(true); + const childSnapshotPromises = renderedIframeRefs.map(async (ref) => { + const childDepth = options.depth ? options.depth - snapshot3.iframeDepths[ref] - 1 : void 0; + const frameRootSelector = `aria-ref=${ref} >> internal:control=enter-frame >> body,frameset`; + try { + return await ariaSnapshotJSONForFrame(progress2, snapshot3.resolvedFrame, frameRootSelector, { ...options, depth: childDepth, strict: false }); + } catch { + return []; + } + }); + const childSnapshots = await Promise.all(childSnapshotPromises); + progress2.setAllowConcurrentOrNestedRaces(false); + const mergeIframeChildren = (node) => { + if (typeof node === "string") + return; + if (node.role === "iframe" && typeof node.ref === "string") { + const childSnapshot = childSnapshots[renderedIframeRefs.indexOf(node.ref)]; + if (childSnapshot?.length) + node.children = childSnapshot; + return; + } + (node.children || []).forEach(mergeIframeChildren); + }; + snapshot3.json.forEach(mergeIframeChildren); + return snapshot3.json; +} +function ensureArrayLimit(array, limit) { + if (array.length > limit) + return array.splice(0, limit / 10); + return []; +} +var PageEvent, navigationMarkSymbol, Page, WorkerEvent, Worker, PageBinding, InitScript; +var init_page = __esm({ + "packages/playwright-core/src/server/page.ts"() { + "use strict"; + init_selectorParser(); + init_manualPromise(); + init_utilityScriptSerializers(); + init_comparators(); + init_debugLogger(); + init_manualPromise(); + init_assert(); + init_stringUtils(); + init_locatorGenerators(); + init_browserContext(); + init_disposable2(); + init_console(); + init_errors(); + init_fileChooser(); + init_frames(); + init_helper(); + init_input(); + init_instrumentation(); + init_javascript(); + init_screenshotter(); + init_highlightController(); + init_callLog(); + init_bindingsControllerSource(); + init_overlay(); + init_dom(); + init_screencast(); + init_javascript(); + PageEvent = { + Close: "close", + Crash: "crash", + Download: "download", + EmulatedSizeChanged: "emulatedsizechanged", + FileChooser: "filechooser", + FrameAttached: "frameattached", + FrameDetached: "framedetached", + InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument", + LocatorHandlerTriggered: "locatorhandlertriggered", + WebSocket: "websocket", + Worker: "worker" + }; + navigationMarkSymbol = /* @__PURE__ */ Symbol("navigationMark"); + Page = class _Page extends SdkObject { + constructor(delegate, browserContext) { + super(browserContext, "page"); + this._lifecycle = "open"; + this.closedPromise = new ManualPromise(); + this._initializedPromise = new ManualPromise(); + this._consoleMessages = []; + this._pageErrors = []; + this.openScope = new LongStandingScope(); + this._emulatedMedia = {}; + this._fileChooserInterceptedBy = /* @__PURE__ */ new Set(); + this._pageBindings = /* @__PURE__ */ new Map(); + this.initScripts = []; + this._workers = /* @__PURE__ */ new Map(); + this.requestInterceptors = []; + this._locatorHandlers = /* @__PURE__ */ new Map(); + this._lastLocatorHandlerUid = 0; + this._locatorHandlerRunningCounter = 0; + this._networkRequests = []; + this.attribution.page = this; + this.delegate = delegate; + this.browserContext = browserContext; + this.keyboard = new Keyboard(delegate.rawKeyboard, this); + this.mouse = new Mouse(delegate.rawMouse, this); + this.touchscreen = new Touchscreen(delegate.rawTouchscreen, this); + this.screenshotter = new Screenshotter(this); + this.highlightController = new HighlightController(this); + this.frameManager = new FrameManager(this); + this.overlay = new Overlay(this); + this.screencast = new Screencast(this); + if (delegate.pdf) + this.pdf = delegate.pdf.bind(delegate); + this.coverage = delegate.coverage ? delegate.coverage() : null; + this.isStorageStatePage = browserContext.isCreatingStorageStatePage(); + } + static { + this.Events = PageEvent; + } + async reportAsNew(opener, error) { + if (this.delegate.noUtilityWorld?.()) { + await this._addInitScript(saveGlobalsSnapshotSource); + await this.safeNonStallingEvaluateInAllFrames(saveGlobalsSnapshotSource, "main"); + } + if (opener) { + const openerPageOrError = await opener.waitForInitializedOrError(); + if (openerPageOrError instanceof _Page && !openerPageOrError.isClosedOrClosingOrCrashed()) + this._opener = openerPageOrError; + } + this._markInitialized(error); + } + _markInitialized(error = void 0) { + if (error) { + if (this.browserContext.isClosingOrClosed()) + return; + this.frameManager.createDummyMainFrameIfNeeded(); + } + this._initialized = error || this; + this.emitOnContext(BrowserContext.Events.Page, this); + for (const pageError of this._pageErrors) + this.emitOnContext(BrowserContext.Events.PageError, pageError, this); + for (const message of this._consoleMessages) + this.emitOnContext(BrowserContext.Events.Console, message); + if (this.isClosed()) + this.emit(_Page.Events.Close); + else if (!this.isStorageStatePage) + this.instrumentation.onPageOpen(this); + this._initializedPromise.resolve(this._initialized); + } + initializedOrUndefined() { + return this._initialized ? this : void 0; + } + waitForInitializedOrError() { + return this._initializedPromise; + } + emitOnContext(event, ...args) { + if (this.isStorageStatePage) + return; + this.browserContext.emit(event, ...args); + } + async resetForReuse(progress2) { + await this.mainFrame().gotoImpl(progress2, "about:blank", {}); + this._emulatedSize = void 0; + this._emulatedMedia = {}; + this._extraHTTPHeaders = void 0; + await progress2.race(Promise.all([ + this.delegate.updateEmulatedViewportSize(), + this.delegate.updateEmulateMedia(), + this.delegate.updateExtraHTTPHeaders() + ])); + await this.delegate.resetForReuse(progress2); + } + _didDisconnect(error) { + if (this.openScope.isClosed()) + return; + this.frameManager.dispose(error); + this.screencast.dispose(); + this.overlay.dispose(); + this.highlightController.dispose(); + this.openScope.close(error); + } + _didClose() { + if (this._lifecycle === "closed") + return; + this._lifecycle = "closed"; + this._didDisconnect(new TargetClosedError(this.closeReason())); + this.emit(_Page.Events.Close); + this.browserContext.emit(BrowserContext.Events.PageClosed, this); + this.closedPromise.resolve(); + if (!this.isStorageStatePage) + this.instrumentation.onPageDidClose(this); + } + _didCrash() { + if (this._lifecycle !== "open") + return; + this._lifecycle = "crashed"; + this._didDisconnect(new TargetClosedError("Page crashed")); + this.emit(_Page.Events.Crash); + } + async _onFileChooserOpened(handle) { + let multiple; + try { + multiple = await handle.evaluate((element3) => !!element3.multiple); + } catch (e) { + return; + } + if (!this.listenerCount(_Page.Events.FileChooser)) { + handle.dispose(); + return; + } + const fileChooser = new FileChooser(handle, multiple); + this.emit(_Page.Events.FileChooser, fileChooser); + } + opener() { + return this._opener; + } + mainFrame() { + return this.frameManager.mainFrame(); + } + frames() { + return this.frameManager.frames(); + } + async exposeBinding(progress2, name, playwrightBinding, noGlobal) { + if (this._pageBindings.has(name)) + throw new Error(`Function "${name}" has been already registered`); + if (this.browserContext._pageBindings.has(name)) + throw new Error(`Function "${name}" has been already registered in the browser context`); + await progress2.race(this.browserContext.exposePlaywrightBindingIfNeeded()); + const binding = new PageBinding(this, name, playwrightBinding, noGlobal); + this._pageBindings.set(name, binding); + try { + await progress2.race(this.delegate.addInitScript(binding.initScript)); + await progress2.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main")); + return binding; + } catch (error) { + this._pageBindings.delete(name); + throw error; + } + } + async removeExposedBinding(binding) { + if (this._pageBindings.get(binding.name) !== binding) + return; + this._pageBindings.delete(binding.name); + await this.delegate.removeInitScripts([binding.initScript]); + const cleanup = `{ ${binding.cleanupScript} };`; + await this.safeNonStallingEvaluateInAllFrames(cleanup, "main"); + } + async setExtraHTTPHeaders(progress2, headers) { + const oldHeaders = this._extraHTTPHeaders; + try { + this._extraHTTPHeaders = headers; + await progress2.race(this.delegate.updateExtraHTTPHeaders()); + } catch (error) { + this._extraHTTPHeaders = oldHeaders; + this.delegate.updateExtraHTTPHeaders().catch(() => { + }); + throw error; + } + } + extraHTTPHeaders() { + return this._extraHTTPHeaders; + } + addNetworkRequest(request2) { + this._networkRequests.push(request2); + ensureArrayLimit(this._networkRequests, 100); + } + networkRequests() { + return this._networkRequests; + } + async onBindingCalled(payload, context) { + if (this.isClosedOrClosingOrCrashed()) + return; + await PageBinding.dispatch(this, payload, context); + } + addConsoleMessage(worker, type3, args, location2, text2, timestamp) { + const message = new ConsoleMessage(this, worker, type3, text2, args, location2, timestamp); + const intercepted = this.frameManager.interceptConsoleMessage(message); + if (intercepted) { + args.forEach((arg2) => arg2.dispose()); + return; + } + this._consoleMessages.push(message); + ensureArrayLimit(this._consoleMessages, 200); + if (this._initialized) + this.emitOnContext(BrowserContext.Events.Console, message); + } + clearConsoleMessages() { + this._consoleMessages.length = 0; + } + consoleMessages(filter2) { + if (filter2 === "all") + return this._consoleMessages; + const marked = this._consoleMessages.findLastIndex((m) => m[navigationMarkSymbol]); + return marked === -1 ? this._consoleMessages : this._consoleMessages.slice(marked + 1); + } + addPageError(error, location2) { + const pageError = { error, location: location2 }; + this._pageErrors.push(pageError); + ensureArrayLimit(this._pageErrors, 200); + if (this._initialized) + this.emitOnContext(BrowserContext.Events.PageError, pageError, this); + } + clearPageErrors() { + this._pageErrors.length = 0; + } + pageErrors(filter2) { + if (filter2 === "all") + return this._pageErrors.map((e) => e.error); + const marked = this._pageErrors.findLastIndex((e) => e[navigationMarkSymbol]); + return (marked === -1 ? this._pageErrors : this._pageErrors.slice(marked + 1)).map((e) => e.error); + } + async reload(progress2, options) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + const [response2] = await Promise.all([ + // Reload must be a new document, and should not be confused with a stray pushState. + this.mainFrame().waitForNavigation(progress2, true, options), + progress2.race(this.delegate.reload()) + ]); + return response2; + }); + } + async goBack(progress2, options) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + let error; + const waitPromise = this.mainFrame().waitForNavigation(progress2, false, options).catch((e) => { + error = e; + return null; + }); + const result2 = await progress2.race(this.delegate.goBack()); + if (!result2) { + waitPromise.catch(() => { + }); + return null; + } + const response2 = await waitPromise; + if (error) + throw error; + return response2; + }); + } + async goForward(progress2, options) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + let error; + const waitPromise = this.mainFrame().waitForNavigation(progress2, false, options).catch((e) => { + error = e; + return null; + }); + const result2 = await progress2.race(this.delegate.goForward()); + if (!result2) { + waitPromise.catch(() => { + }); + return null; + } + const response2 = await waitPromise; + if (error) + throw error; + return response2; + }); + } + requestGC(progress2) { + return progress2.race(this.delegate.requestGC()); + } + registerLocatorHandler(selector, noWaitAfter) { + const uid = ++this._lastLocatorHandlerUid; + this._locatorHandlers.set(uid, { selector, noWaitAfter }); + return uid; + } + resolveLocatorHandler(uid, remove) { + const handler = this._locatorHandlers.get(uid); + if (remove) + this._locatorHandlers.delete(uid); + if (handler) { + handler.resolved?.resolve(); + handler.resolved = void 0; + } + } + unregisterLocatorHandler(uid) { + this._locatorHandlers.delete(uid); + } + async performActionPreChecks(progress2) { + await this._performWaitForNavigationCheck(progress2); + await this._performLocatorHandlersCheckpoint(progress2); + await this._performWaitForNavigationCheck(progress2); + } + async _performWaitForNavigationCheck(progress2) { + if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK) + return; + const mainFrame = this.frameManager.mainFrame(); + if (!mainFrame || !mainFrame.pendingDocument()) + return; + const url3 = mainFrame.pendingDocument()?.request?.url(); + const toUrl = url3 ? ` "${trimStringWithEllipsis(url3, 200)}"` : ""; + progress2.log(` waiting for${toUrl} navigation to finish...`); + await helper.waitForEvent(progress2, mainFrame, Frame.Events.InternalNavigation, (e) => { + if (!e.isPublic) + return false; + if (!e.error) + progress2.log(` navigated to "${trimStringWithEllipsis(mainFrame.url(), 200)}"`); + return true; + }).promise; + } + async _performLocatorHandlersCheckpoint(progress2) { + if (this._locatorHandlerRunningCounter) + return; + for (const [uid, handler] of this._locatorHandlers) { + if (!handler.resolved) { + if (await this.mainFrame().isVisibleInternal(progress2, { selector: handler.selector, strict: true })) { + handler.resolved = new ManualPromise(); + this.emit(_Page.Events.LocatorHandlerTriggered, uid); + } + } + if (handler.resolved) { + ++this._locatorHandlerRunningCounter; + progress2.log(` found ${asLocator(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`); + const promise = handler.resolved.then(async () => { + if (!handler.noWaitAfter) { + progress2.log(` locator handler has finished, waiting for ${asLocator(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`); + await this.mainFrame().waitForSelector(progress2, { selector: handler.selector }, false, { state: "hidden" }); + } else { + progress2.log(` locator handler has finished`); + } + }); + try { + progress2.setAllowConcurrentOrNestedRaces(true); + await progress2.race(this.openScope.race(promise)); + } finally { + progress2.setAllowConcurrentOrNestedRaces(false); + --this._locatorHandlerRunningCounter; + } + progress2.log(` interception handler has finished, continuing`); + } + } + } + async emulateMedia(progress2, options) { + const oldEmulatedMedia = { ...this._emulatedMedia }; + if (options.media !== void 0) + this._emulatedMedia.media = options.media; + if (options.colorScheme !== void 0) + this._emulatedMedia.colorScheme = options.colorScheme; + if (options.reducedMotion !== void 0) + this._emulatedMedia.reducedMotion = options.reducedMotion; + if (options.forcedColors !== void 0) + this._emulatedMedia.forcedColors = options.forcedColors; + if (options.contrast !== void 0) + this._emulatedMedia.contrast = options.contrast; + try { + await progress2.race(this.delegate.updateEmulateMedia()); + } catch (error) { + this._emulatedMedia = oldEmulatedMedia; + this.delegate.updateEmulateMedia().catch(() => { + }); + throw error; + } + } + emulatedMedia() { + const contextOptions = this.browserContext._options; + return { + media: this._emulatedMedia.media || "no-override", + colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light", + reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference", + forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none", + contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference" + }; + } + async setViewportSize(progress2, viewportSize) { + const oldEmulatedSize = this._emulatedSize; + try { + this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } }); + await progress2.race(this.delegate.updateEmulatedViewportSize()); + } catch (error) { + this._emulatedSize = oldEmulatedSize; + this.delegate.updateEmulatedViewportSize().catch(() => { + }); + throw error; + } + } + setEmulatedSizeFromWindowOpen(emulatedSize) { + this._setEmulatedSize(emulatedSize); + } + _setEmulatedSize(emulatedSize) { + this._emulatedSize = emulatedSize; + this.emit(_Page.Events.EmulatedSizeChanged); + } + emulatedSize() { + if (this._emulatedSize) + return this._emulatedSize; + const contextOptions = this.browserContext._options; + return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0; + } + async bringToFront(progress2) { + await progress2.race(this.delegate.bringToFront()); + } + async addInitScript(progress2, source14) { + return await progress2.race(this._addInitScript(source14)); + } + async _addInitScript(source14) { + const initScript = new InitScript(this, source14); + this.initScripts.push(initScript); + try { + await this.delegate.addInitScript(initScript); + } catch (error) { + initScript.dispose().catch(() => { + }); + throw error; + } + return initScript; + } + async removeInitScript(initScript) { + this.initScripts = this.initScripts.filter((script) => initScript !== script); + await this.delegate.removeInitScripts([initScript]); + } + needsRequestInterception() { + return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0; + } + async addRequestInterceptor(progress2, handler, prepend) { + if (prepend) + this.requestInterceptors.unshift(handler); + else + this.requestInterceptors.push(handler); + await progress2.race(this.delegate.updateRequestInterception()); + } + async removeRequestInterceptor(handler) { + const index = this.requestInterceptors.indexOf(handler); + if (index === -1) + return; + this.requestInterceptors.splice(index, 1); + await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler); + await this.delegate.updateRequestInterception(); + } + async expectScreenshot(progress2, options) { + const locator3 = options.locator; + const rafrafScreenshot = locator3 ? async (progress3, timeout) => { + return await locator3.frame.rafrafTimeoutScreenshotElementWithProgress(progress3, locator3.selector, timeout, options || {}); + } : async (progress3, timeout) => { + await this.performActionPreChecks(progress3); + await this.mainFrame().rafrafTimeout(progress3, timeout); + return await this.screenshotter.screenshotPage(progress3, options || {}); + }; + let intermediateResult; + try { + if (!options.expected && options.isNot) + throw new Error('"not" matcher requires expected result'); + const format2 = validateScreenshotOptions(options || {}); + const comparator = getComparator(`image/${format2}`); + const areEqualScreenshots = (actual2, expected, previous2) => { + const comparatorResult = actual2 && expected ? comparator(actual2, expected, options) : void 0; + if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot) + return true; + if (comparatorResult) + intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual: actual2, previous: previous2 }; + return false; + }; + let actual; + let previous; + const pollIntervals = [0, 100, 250, 500]; + if (options.expected) + progress2.log(` verifying given screenshot expectation`); + else + progress2.log(` generating new stable screenshot expectation`); + let isFirstIteration = true; + while (true) { + if (this.isClosed()) + throw new Error("The page has closed"); + const screenshotTimeout = pollIntervals.shift() ?? 1e3; + if (screenshotTimeout) + progress2.log(`waiting ${screenshotTimeout}ms before taking screenshot`); + previous = actual; + actual = await rafrafScreenshot(progress2, screenshotTimeout).catch((e) => { + if (this.mainFrame().isNonRetriableError(e)) + throw e; + progress2.log(`failed to take screenshot - ` + e.message); + return void 0; + }); + if (!actual) + continue; + const expectation = options.expected && isFirstIteration ? options.expected : previous; + if (areEqualScreenshots(actual, expectation, previous)) + break; + if (intermediateResult) + progress2.log(intermediateResult.errorMessage); + isFirstIteration = false; + } + if (!isFirstIteration) + progress2.log(`captured a stable screenshot`); + if (!options.expected) + return { actual }; + if (isFirstIteration) { + progress2.log(`screenshot matched expectation`); + return {}; + } + if (areEqualScreenshots(actual, options.expected, void 0)) { + progress2.log(`screenshot matched expectation`); + return {}; + } + throw new Error(intermediateResult.errorMessage); + } catch (e) { + if (isJavaScriptErrorInEvaluate(e) || isInvalidSelectorError(e)) + throw e; + let errorMessage = e.message; + if (e instanceof TimeoutError && intermediateResult?.previous) + errorMessage = `Failed to take two consecutive stable screenshots.`; + const details = { + log: compressCallLog(e.message ? [...progress2.metadata.log, e.message] : progress2.metadata.log), + actual: intermediateResult?.actual, + previous: intermediateResult?.previous, + diff: intermediateResult?.diff, + timedOut: e instanceof TimeoutError, + customErrorMessage: errorMessage + }; + const error = new Error("Expect failed"); + error.details = details; + throw error; + } + } + async screenshot(progress2, options) { + return await this.screenshotter.screenshotPage(progress2, options); + } + async close(progress2, options = {}) { + await progress2.race(this._close(options)); + } + async _close(options = {}) { + if (this._lifecycle === "closed") + return; + if (options.reason) + this._closeReason = options.reason; + if (!this.isStorageStatePage) + await this.instrumentation.onPageWillClose(this).catch(() => { + }); + await this.screencast.handlePageOrContextClose(); + if (this._lifecycle !== "closing") { + this._lifecycle = "closing"; + const closePage = this._customCloseHandler ?? ((runBeforeUnload) => this.delegate.closePage(runBeforeUnload)); + await closePage(false).catch((e) => debugLogger.log("error", e)); + } + await this.closedPromise; + } + setCustomCloseHandler(handler) { + this._customCloseHandler = handler; + } + async runBeforeUnload(progress2) { + await progress2.race(this._runBeforeUnload()); + } + async _runBeforeUnload() { + const closePage = this._customCloseHandler ?? ((runBeforeUnload) => this.delegate.closePage(runBeforeUnload)); + await closePage(true).catch((e) => debugLogger.log("error", e)); + } + isClosed() { + return this._lifecycle === "closed"; + } + isClosedOrClosingOrCrashed() { + return this._lifecycle !== "open"; + } + addWorker(workerId, worker) { + this._workers.set(workerId, worker); + this.emit(_Page.Events.Worker, worker); + } + removeWorker(workerId) { + const worker = this._workers.get(workerId); + if (!worker) + return; + worker.didClose(); + this._workers.delete(workerId); + } + clearWorkers() { + for (const [workerId, worker] of this._workers) { + worker.didClose(); + this._workers.delete(workerId); + } + } + async setFileChooserInterceptedBy(progress2, enabled, by) { + await progress2.race(this._setFileChooserInterceptedBy(enabled, by)); + } + async _setFileChooserInterceptedBy(enabled, by) { + const wasIntercepted = this.fileChooserIntercepted(); + if (enabled) + this._fileChooserInterceptedBy.add(by); + else + this._fileChooserInterceptedBy.delete(by); + if (wasIntercepted !== this.fileChooserIntercepted()) + await this.delegate.updateFileChooserInterception(); + } + fileChooserIntercepted() { + return this._fileChooserInterceptedBy.size > 0; + } + frameNavigatedToNewDocument(frame) { + this.emit(_Page.Events.InternalFrameNavigatedToNewDocument, frame); + this.browserContext.emit(BrowserContext.Events.InternalFrameNavigatedToNewDocument, frame); + const origin = frame.origin(); + if (origin) + this.browserContext.addVisitedOrigin(origin); + if (frame === this.mainFrame()) { + if (this._consoleMessages.length > 0) + this._consoleMessages[this._consoleMessages.length - 1][navigationMarkSymbol] = true; + if (this._pageErrors.length > 0) + this._pageErrors[this._pageErrors.length - 1][navigationMarkSymbol] = true; + } + } + allInitScripts() { + const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript); + if (this.browserContext.bindingsInitScript) + bindings.unshift(this.browserContext.bindingsInitScript); + return [...bindings, ...this.browserContext.initScripts, ...this.initScripts]; + } + getBinding(name) { + return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name); + } + async safeNonStallingEvaluateInAllFrames(expression2, world, options = {}) { + await Promise.all(this.frames().map(async (frame) => { + try { + await frame.nonStallingEvaluateInExistingContext(expression2, world); + } catch (e) { + if (options.throwOnJSErrors && isJavaScriptErrorInEvaluate(e)) + throw e; + } + })); + } + async setDockTile(image) { + await this.delegate.setDockTile(image); + } + async webStorageItems(progress2, kind) { + const storage = `${kind}Storage`; + return await this.mainFrame().evaluateExpression(progress2, `(() => { + const result = []; + for (let i = 0; i < ${storage}.length; i++) { + const name = ${storage}.key(i); + if (name !== null) + result.push({ name, value: ${storage}.getItem(name) ?? '' }); + } + return result; + })()`, { world: "utility" }); + } + async webStorageGetItem(progress2, kind, name) { + const value2 = await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.getItem(${JSON.stringify(name)})`, { world: "utility" }); + return value2 === null ? void 0 : value2; + } + async webStorageSetItem(progress2, kind, name, value2) { + await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.setItem(${JSON.stringify(name)}, ${JSON.stringify(value2)})`, { world: "utility" }); + } + async webStorageRemoveItem(progress2, kind, name) { + await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.removeItem(${JSON.stringify(name)})`, { world: "utility" }); + } + async webStorageClear(progress2, kind) { + await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.clear()`, { world: "utility" }); + } + }; + WorkerEvent = { + Console: "console", + Close: "close" + }; + Worker = class _Worker extends SdkObject { + constructor(parent, url3, onDisconnect) { + super(parent, "worker"); + this._executionContextPromise = new ManualPromise(); + this._workerScriptLoaded = false; + this.existingExecutionContext = null; + this.openScope = new LongStandingScope(); + this.attribution.worker = this; + this.url = url3; + this._onDisconnect = onDisconnect; + } + static { + this.Events = WorkerEvent; + } + createExecutionContext(delegate) { + this.existingExecutionContext = new ExecutionContext(this, delegate, "worker"); + if (this._workerScriptLoaded) + this._executionContextPromise.resolve(this.existingExecutionContext); + return this.existingExecutionContext; + } + destroyExecutionContext(errorMessage) { + if (this.existingExecutionContext) + this.existingExecutionContext.contextDestroyed(errorMessage); + this.existingExecutionContext = null; + this._workerScriptLoaded = false; + this._executionContextPromise = new ManualPromise(); + } + workerScriptLoaded() { + this._workerScriptLoaded = true; + if (this.existingExecutionContext) + this._executionContextPromise.resolve(this.existingExecutionContext); + } + didClose() { + if (this.existingExecutionContext) + this.existingExecutionContext.contextDestroyed("Worker was closed"); + this.emit(_Worker.Events.Close, this); + this.openScope.close(new Error("Worker closed")); + } + async evaluateExpression(progress2, expression2, isFunction2, arg2) { + return progress2.race(evaluateExpression(await this._executionContextPromise, expression2, { returnByValue: true, isFunction: isFunction2 }, arg2)); + } + async evaluateExpressionHandle(progress2, expression2, isFunction2, arg2) { + return progress2.race(evaluateExpression(await this._executionContextPromise, expression2, { returnByValue: false, isFunction: isFunction2 }, arg2)); + } + async disconnect(progress2, options = {}) { + if (!this._onDisconnect) + throw new Error("Cannot disconnect from this worker"); + this._closeReason = options.reason; + await progress2.race(this._onDisconnect()); + } + }; + PageBinding = class _PageBinding extends DisposableObject { + static { + this.kBindingName = "__playwright__binding__"; + } + static createInitScript(browserContext) { + return new InitScript(browserContext, ` + (() => { + const module = {}; + ${source6} + const property = '${kBindingsControllerProperty}'; + if (!globalThis[property]) + globalThis[property] = new (module.exports.BindingsController())(globalThis, '${_PageBinding.kBindingName}'); + })(); + `); + } + constructor(parent, name, playwrightFunction, noGlobal) { + super(parent); + this.name = name; + this.playwrightFunction = playwrightFunction; + this.initScript = new InitScript(parent, `globalThis['${kBindingsControllerProperty}'].addBinding(${JSON.stringify(name)}, ${!!noGlobal})`); + this.cleanupScript = `globalThis['${kBindingsControllerProperty}'].removeBinding(${JSON.stringify(name)})`; + } + static async dispatch(page, payload, context) { + const { name, seq, serializedArgs } = JSON.parse(payload); + try { + assert(context.world); + const binding = page.getBinding(name); + if (!binding) + throw new Error(`Function "${name}" is not exposed`); + if (!Array.isArray(serializedArgs)) + throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`); + const args = serializedArgs.map((a) => parseEvaluationResultValue(a)); + const result2 = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, ...args); + context.evaluateExpressionHandle(`arg => globalThis['${kBindingsControllerProperty}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result: result2 }).catch((e) => debugLogger.log("error", e)); + } catch (error) { + context.evaluateExpressionHandle(`arg => globalThis['${kBindingsControllerProperty}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => debugLogger.log("error", e)); + } + } + async dispose() { + await this.parent.removeExposedBinding(this); + } + }; + InitScript = class extends DisposableObject { + constructor(owner2, source14) { + super(owner2); + this.source = `(() => { + ${source14} + })();`; + } + async dispose() { + await this.parent.removeInitScript(this); + } + }; + } +}); + +// packages/playwright-core/src/server/types.ts +var kLifecycleEvents; +var init_types = __esm({ + "packages/playwright-core/src/server/types.ts"() { + "use strict"; + kLifecycleEvents = /* @__PURE__ */ new Set(["load", "domcontentloaded", "networkidle", "commit"]); + } +}); + +// packages/playwright-core/src/generated/webMCPSource.ts +var source7; +var init_webMCPSource = __esm({ + "packages/playwright-core/src/generated/webMCPSource.ts"() { + "use strict"; + source7 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/webMCP.ts\nvar webMCP_exports = {};\n__export(webMCP_exports, {\n WebMCPScript: () => WebMCPScript\n});\nmodule.exports = __toCommonJS(webMCP_exports);\nvar WebMCPScript = class {\n constructor(global) {\n var _a, _b, _c;\n this._global = global;\n this._modelContext = (_c = (_a = global.document) == null ? void 0 : _a.modelContext) != null ? _c : (_b = global.navigator) == null ? void 0 : _b.modelContext;\n }\n async tools() {\n return (await this._ownTools()).map((tool) => this._describe(tool));\n }\n async callTool(name, input) {\n const modelContext = this._modelContext;\n if (!modelContext)\n throw new Error("WebMCP is not available on this page");\n if (modelContext.invokeTool)\n return await modelContext.invokeTool(name, input);\n const tool = (await this._ownTools()).find((tool2) => tool2.name === name);\n if (!tool || !modelContext.executeTool)\n throw new Error(`WebMCP tool "${name}" is not registered in this frame`);\n return this._parseResult(await this._executeTool(modelContext, tool, input));\n }\n async _executeTool(modelContext, tool, input) {\n try {\n return await modelContext.executeTool(tool, input);\n } catch (e) {\n if (!String(e == null ? void 0 : e.message).includes("Failed to parse input"))\n throw e;\n return await modelContext.executeTool(tool, JSON.stringify(input));\n }\n }\n _parseResult(result) {\n if (typeof result !== "string")\n return result;\n if (result === "undefined")\n return void 0;\n try {\n return JSON.parse(result);\n } catch {\n return result;\n }\n }\n async _ownTools() {\n var _a, _b, _c;\n const tools = (_c = await ((_b = (_a = this._modelContext) == null ? void 0 : _a.getTools) == null ? void 0 : _b.call(_a))) != null ? _c : [];\n return tools.filter((tool) => !("window" in tool) || tool.window === this._global.window);\n }\n _describe(tool) {\n var _a;\n const annotations = tool.annotations;\n return {\n name: tool.name,\n description: (_a = tool.description) != null ? _a : "",\n inputSchema: this._parseInputSchema(tool.inputSchema),\n annotations: annotations ? {\n readOnly: annotations.readOnlyHint,\n untrustedContent: annotations.untrustedContentHint,\n consequential: annotations.consequentialHint\n } : void 0\n };\n }\n _parseInputSchema(inputSchema) {\n if (typeof inputSchema !== "string")\n return inputSchema;\n try {\n return JSON.parse(inputSchema);\n } catch {\n return void 0;\n }\n }\n};\n'; + } +}); + +// packages/playwright-core/src/server/webmcp.ts +function assertBrowserSupport(page) { + const { name, browserType, browserProcess, originalLaunchOptions } = page.browserContext._browser.options; + if (browserType === "webkit") + throw new Error("WebMCP is not supported in WebKit."); + if (!browserProcess.process || name !== "chromium" && name !== "firefox") + return; + if (browserType === "chromium") { + const features = (originalLaunchOptions.args ?? []).filter((arg2) => arg2.startsWith("--enable-features=")).flatMap((arg2) => arg2.substring("--enable-features=".length).split(",")); + if (!features.includes("WebMCP")) + throw new Error('WebMCP is not enabled. Launch the browser with the "--enable-features=WebMCP" argument.'); + } else { + const prefs = originalLaunchOptions.firefoxUserPrefs; + if (prefs?.["dom.modelcontext.enabled"] !== true || prefs?.["dom.modelcontext.testing.enabled"] !== true) + throw new Error('WebMCP is not enabled. Launch the browser with the "dom.modelcontext.enabled" and "dom.modelcontext.testing.enabled" preferences set to true.'); + } +} +function normalizeTool(tool) { + const annotations = {}; + if (tool.annotations?.readOnly) + annotations.readOnly = true; + if (tool.annotations?.untrustedContent) + annotations.untrustedContent = true; + if (tool.annotations?.consequential) + annotations.consequential = true; + return { + name: tool.name, + description: tool.description, + ...tool.inputSchema !== void 0 ? { inputSchema: tool.inputSchema } : {}, + ...Object.keys(annotations).length ? { annotations } : {} + }; +} +var kScriptSource, WebMCP; +var init_webmcp = __esm({ + "packages/playwright-core/src/server/webmcp.ts"() { + "use strict"; + init_webMCPSource(); + kScriptSource = `(() => { + const module = {}; + ${source7} + return new (module.exports.WebMCPScript())(globalThis); +})()`; + WebMCP = class { + constructor(frame) { + this._frame = frame; + } + async tools(progress2) { + assertBrowserSupport(this._frame._page); + const tools = await this._frame.evaluateExpression(progress2, `${kScriptSource}.tools()`, { world: "utility" }); + return tools.map(normalizeTool); + } + async callTool(progress2, name, input) { + const tools = await this.tools(progress2); + if (!tools.some((tool) => tool.name === name)) { + const available = tools.map((tool) => tool.name); + throw new Error(`No WebMCP tool named "${name}".` + (available.length ? ` Available tools: ${available.join(", ")}.` : " The frame does not register any WebMCP tools.")); + } + const world = this._frame._page.browserContext._browser.options.browserType === "firefox" ? "main" : "utility"; + return await this._frame.evaluateExpression(progress2, `params => ${kScriptSource}.callTool(params.name, params.input)`, { isFunction: true, world }, { name, input: input ?? {} }); + } + }; + } +}); + +// packages/playwright-core/src/server/frames.ts +function verifyLifecycle(name, waitUntil) { + if (waitUntil === "networkidle0") + waitUntil = "networkidle"; + if (!kLifecycleEvents.has(waitUntil)) + throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`); + return waitUntil; +} +function renderUnexpectedValue(expression2, received) { + if (expression2 === "to.match.aria") + return received ? received.raw : received; + return received; +} +var yaml, NavigationAbortedError, ExpectError, kDummyFrameId, FrameManager, FrameEvent, Frame, SignalBarrier; +var init_frames = __esm({ + "packages/playwright-core/src/server/frames.ts"() { + "use strict"; + init_ariaSnapshot(); + init_ariaSnapshotRenderer(); + init_selectorParser(); + init_manualPromise(); + init_eventsHelper(); + init_manualPromise(); + init_locatorGenerators(); + init_assert(); + init_urlMatch(); + init_crypto(); + init_browserContext(); + init_dom(); + init_errors(); + init_fileUploadUtils(); + init_frameSelectors(); + init_helper(); + init_instrumentation(); + init_javascript(); + init_network2(); + init_page(); + init_progress(); + init_types(); + init_protocolError(); + init_webmcp(); + yaml = require("./utilsBundle").yaml; + NavigationAbortedError = class extends Error { + constructor(documentId, message) { + super(message); + this.documentId = documentId; + } + }; + ExpectError = class extends Error { + constructor(details) { + super("Expect failed"); + this.name = "ExpectError"; + this.details = details; + } + }; + kDummyFrameId = ""; + FrameManager = class { + constructor(page) { + this._frames = /* @__PURE__ */ new Map(); + this._consoleMessageTags = /* @__PURE__ */ new Map(); + this._signalBarriers = /* @__PURE__ */ new Set(); + this._webSockets = /* @__PURE__ */ new Map(); + this._nextFrameSeq = 0; + this._page = page; + this._mainFrame = void 0; + } + _allocateFrameSeq() { + return this._nextFrameSeq++; + } + createDummyMainFrameIfNeeded() { + if (!this._mainFrame) + this.frameAttached(kDummyFrameId, null); + } + dispose(error) { + for (const frame of this._frames.values()) { + frame._stopNetworkIdleTimer(); + frame.invalidateNonStallingEvaluations(error); + } + } + mainFrame() { + return this._mainFrame; + } + frames() { + const frames = []; + collect(this._mainFrame); + return frames; + function collect(frame) { + frames.push(frame); + for (const subframe of frame.childFrames()) + collect(subframe); + } + } + frame(frameId) { + return this._frames.get(frameId) || null; + } + frameAttached(frameId, parentFrameId) { + const parentFrame = parentFrameId ? this._frames.get(parentFrameId) : null; + if (!parentFrame) { + if (this._mainFrame) { + this._frames.delete(this._mainFrame._id); + this._mainFrame._id = frameId; + } else { + assert(!this._frames.has(frameId)); + this._mainFrame = new Frame(this._page, frameId, parentFrame); + } + this._frames.set(frameId, this._mainFrame); + return this._mainFrame; + } else { + assert(!this._frames.has(frameId)); + const frame = new Frame(this._page, frameId, parentFrame); + this._frames.set(frameId, frame); + this._page.emit(Page.Events.FrameAttached, frame); + this._page.browserContext.emit(BrowserContext.Events.FrameAttached, frame); + return frame; + } + } + async waitForSignalsCreatedBy(progress2, waitAfter, action) { + if (!waitAfter) + return action(progress2); + const barrier = new SignalBarrier(progress2); + this._signalBarriers.add(barrier); + try { + const result2 = await action(progress2); + await progress2.race(this._page.delegate.inputActionEpilogue()); + await barrier.waitFor(progress2); + await new Promise((f) => setImmediate(f)); + return result2; + } finally { + this._signalBarriers.delete(barrier); + } + } + frameWillPotentiallyRequestNavigation() { + for (const barrier of this._signalBarriers) + barrier.retain(); + } + frameDidPotentiallyRequestNavigation() { + for (const barrier of this._signalBarriers) + barrier.release(); + } + frameRequestedNavigation(frameId, documentId) { + const frame = this._frames.get(frameId); + if (!frame) + return; + for (const barrier of this._signalBarriers) + barrier.addFrameNavigation(frame); + if (frame.pendingDocument() && frame.pendingDocument().documentId === documentId) { + return; + } + const request2 = documentId ? Array.from(frame._inflightRequests).find((request3) => request3._documentId === documentId) : void 0; + frame._setPendingDocument({ documentId, request: request2 }); + } + frameCommittedNewDocumentNavigation(frameId, url3, name, documentId, initial) { + const frame = this._frames.get(frameId); + this.removeChildFramesRecursively(frame); + this._clearWebSockets(frame); + const previousUrl = frame._url; + frame._url = url3; + frame._name = name; + let keepPending; + const pendingDocument = frame.pendingDocument(); + if (pendingDocument) { + if (pendingDocument.documentId === void 0) { + pendingDocument.documentId = documentId; + } + if (pendingDocument.documentId === documentId) { + frame._currentDocument = pendingDocument; + } else { + keepPending = pendingDocument; + frame._currentDocument = { documentId, request: void 0 }; + } + frame._setPendingDocument(void 0); + } else { + frame._currentDocument = { documentId, request: void 0 }; + } + frame._onClearLifecycle(); + const navigationEvent = { url: url3, name, newDocument: frame._currentDocument, isPublic: true }; + this._fireInternalFrameNavigation(frame, navigationEvent); + if (!initial) { + frame.apiLog(` navigated to "${url3}"`); + this._page.frameNavigatedToNewDocument(frame); + if (frame === this._mainFrame && previousUrl && previousUrl !== "about:blank") + frame.seq = this._allocateFrameSeq(); + } + frame._setPendingDocument(keepPending); + } + frameCommittedSameDocumentNavigation(frameId, url3) { + const frame = this._frames.get(frameId); + if (!frame) + return; + const pending = frame.pendingDocument(); + if (pending && pending.documentId === void 0 && pending.request === void 0) { + frame._setPendingDocument(void 0); + } + frame._url = url3; + const navigationEvent = { url: url3, name: frame._name, isPublic: true }; + this._fireInternalFrameNavigation(frame, navigationEvent); + frame.apiLog(` navigated to "${url3}"`); + } + frameAbortedNavigation(frameId, errorText, documentId) { + const frame = this._frames.get(frameId); + if (!frame || !frame.pendingDocument()) + return; + if (documentId !== void 0 && frame.pendingDocument().documentId !== documentId) + return; + const navigationEvent = { + url: frame._url, + name: frame._name, + newDocument: frame.pendingDocument(), + error: new NavigationAbortedError(documentId, errorText), + isPublic: !(documentId && frame._redirectedNavigations.has(documentId)) + }; + frame._setPendingDocument(void 0); + this._fireInternalFrameNavigation(frame, navigationEvent); + } + frameDetached(frameId) { + const frame = this._frames.get(frameId); + if (frame) { + this._removeFramesRecursively(frame); + this._page.mainFrame()._recalculateNetworkIdle(); + } + } + frameLifecycleEvent(frameId, event) { + const frame = this._frames.get(frameId); + if (frame) + frame.onLifecycleEvent(event); + } + requestStarted(request2, route2) { + const frame = request2.frame(); + this._inflightRequestStarted(request2); + if (frame && request2._documentId) + frame._setPendingDocument({ documentId: request2._documentId, request: request2 }); + if (request2._isFavicon) { + route2?.abort("aborted").catch(() => { + }); + return; + } + this._page.addNetworkRequest(request2); + this._page.emitOnContext(BrowserContext.Events.Request, request2); + if (route2) + new Route(request2, route2).handle([...this._page.requestInterceptors, ...this._page.browserContext.requestInterceptors]); + } + requestReceivedResponse(response2) { + if (response2.request()._isFavicon) + return; + this._page.emitOnContext(BrowserContext.Events.Response, response2); + } + reportRequestFinished(request2, response2) { + this._inflightRequestFinished(request2); + if (request2._isFavicon) + return; + this._page.emitOnContext(BrowserContext.Events.RequestFinished, { request: request2, response: response2 }); + } + requestFailed(request2, canceled) { + const frame = request2.frame(); + this._inflightRequestFinished(request2); + if (frame && frame.pendingDocument() && frame.pendingDocument().request === request2) { + let errorText = request2.failure().errorText; + if (canceled) + errorText += "; maybe frame was detached?"; + this.frameAbortedNavigation(frame._id, errorText, frame.pendingDocument().documentId); + } + if (request2._isFavicon) + return; + this._page.emitOnContext(BrowserContext.Events.RequestFailed, request2); + } + removeChildFramesRecursively(frame) { + for (const child of frame.childFrames()) + this._removeFramesRecursively(child); + } + _removeFramesRecursively(frame) { + this.removeChildFramesRecursively(frame); + frame._onDetached(); + this._frames.delete(frame._id); + if (!this._page.isClosed()) + this._page.emit(Page.Events.FrameDetached, frame); + } + _inflightRequestFinished(request2) { + const frame = request2.frame(); + if (this._isExcludedFromNetworkIdle(request2) || !frame) + return; + if (!frame._inflightRequests.has(request2)) + return; + frame._inflightRequests.delete(request2); + if (frame._inflightRequests.size === 0) + frame._startNetworkIdleTimer(); + } + _inflightRequestStarted(request2) { + const frame = request2.frame(); + if (this._isExcludedFromNetworkIdle(request2) || !frame) + return; + frame._inflightRequests.add(request2); + if (frame._inflightRequests.size === 1) + frame._stopNetworkIdleTimer(); + } + _isExcludedFromNetworkIdle(request2) { + if (request2._isFavicon) + return true; + if (request2.resourceType() === "eventsource") + return true; + return false; + } + interceptConsoleMessage(message) { + if (message.type() !== "debug") + return false; + const tag = message.text(); + const handler = this._consoleMessageTags.get(tag); + if (!handler) + return false; + this._consoleMessageTags.delete(tag); + handler(); + return true; + } + _clearWebSockets(frame) { + if (frame.parentFrame()) + return; + this._webSockets.clear(); + } + onWebSocketCreated(requestId, url3) { + const ws4 = new WebSocket(this._page, url3); + this._webSockets.set(requestId, ws4); + } + onWebSocketRequest(requestId, requestData) { + const ws4 = this._webSockets.get(requestId); + if (!ws4) + return; + ws4.setWallTimeMs(requestData.wallTimeMs); + if (ws4.markAsNotified()) { + this._page.emit(Page.Events.WebSocket, ws4); + this._page.browserContext.emit(BrowserContext.Events.WebSocket, ws4, this._page); + } + ws4.requestSent(requestData.headers); + } + onWebSocketResponse(requestId, responseData) { + const ws4 = this._webSockets.get(requestId); + if (!ws4) + return; + ws4.responseReceived(responseData.status, responseData.statusText, responseData.headers); + if (responseData.status >= 400) + ws4.error(`${responseData.statusText}: ${responseData.status}`); + } + onWebSocketFrameSent(requestId, opcode, data, wallTimeMs) { + const ws4 = this._webSockets.get(requestId); + if (ws4) + ws4.frameSent(opcode, data, wallTimeMs); + } + webSocketFrameReceived(requestId, opcode, data, wallTimeMs) { + const ws4 = this._webSockets.get(requestId); + if (ws4) + ws4.frameReceived(opcode, data, wallTimeMs); + } + webSocketClosed(requestId) { + const ws4 = this._webSockets.get(requestId); + if (ws4) { + if (ws4.markAsNotified()) { + this._page.emit(Page.Events.WebSocket, ws4); + this._page.browserContext.emit(BrowserContext.Events.WebSocket, ws4, this._page); + } + ws4.closed(); + } + this._webSockets.delete(requestId); + } + webSocketError(requestId, errorMessage) { + const ws4 = this._webSockets.get(requestId); + if (ws4) { + if (ws4.markAsNotified()) { + this._page.emit(Page.Events.WebSocket, ws4); + this._page.browserContext.emit(BrowserContext.Events.WebSocket, ws4, this._page); + } + ws4.error(errorMessage); + } + } + _fireInternalFrameNavigation(frame, event) { + frame.emit(Frame.Events.InternalNavigation, event); + } + }; + FrameEvent = { + InternalNavigation: "internalnavigation", + AddLifecycle: "addlifecycle", + RemoveLifecycle: "removelifecycle" + }; + Frame = class _Frame extends SdkObject { + constructor(page, id, parentFrame) { + super(page, "frame"); + this._firedLifecycleEvents = /* @__PURE__ */ new Set(); + this._firedNetworkIdleSelf = false; + this._url = ""; + this._contextData = /* @__PURE__ */ new Map(); + this._childFrames = /* @__PURE__ */ new Set(); + this._name = ""; + this._inflightRequests = /* @__PURE__ */ new Set(); + this._detachedScope = new LongStandingScope(); + this._raceAgainstEvaluationStallingEventsPromises = /* @__PURE__ */ new Set(); + this._redirectedNavigations = /* @__PURE__ */ new Map(); + this.attribution.frame = this; + this.seq = page.frameManager._allocateFrameSeq(); + this.webmcp = new WebMCP(this); + this._id = id; + this._page = page; + this._parentFrame = parentFrame; + this._currentDocument = { documentId: void 0, request: void 0 }; + this.selectors = new FrameSelectors(this); + this._contextData.set("main", { contextPromise: new ManualPromise(), context: null }); + this._contextData.set("utility", { contextPromise: new ManualPromise(), context: null }); + this._setContext("main", null); + this._setContext("utility", null); + if (this._parentFrame) + this._parentFrame._childFrames.add(this); + this._firedLifecycleEvents.add("commit"); + if (id !== kDummyFrameId) + this._startNetworkIdleTimer(); + } + static { + this.Events = FrameEvent; + } + _isDetached() { + return this._detachedScope.isClosed(); + } + onLifecycleEvent(event) { + if (this._firedLifecycleEvents.has(event)) + return; + this._firedLifecycleEvents.add(event); + this.emit(_Frame.Events.AddLifecycle, event); + if (this === this._page.mainFrame() && this._url !== "about:blank") + this.apiLog(` "${event}" event fired`); + this._page.mainFrame()._recalculateNetworkIdle(); + } + _onClearLifecycle() { + for (const event of this._firedLifecycleEvents) + this.emit(_Frame.Events.RemoveLifecycle, event); + this._firedLifecycleEvents.clear(); + this._inflightRequests = new Set(Array.from(this._inflightRequests).filter((request2) => request2 === this._currentDocument.request)); + this._stopNetworkIdleTimer(); + if (this._inflightRequests.size === 0) + this._startNetworkIdleTimer(); + this._page.mainFrame()._recalculateNetworkIdle(this); + this.onLifecycleEvent("commit"); + } + _setPendingDocument(documentInfo) { + this._pendingDocument = documentInfo; + if (documentInfo) + this.invalidateNonStallingEvaluations(new EvaluationStalledError("Navigation interrupted the evaluation")); + } + pendingDocument() { + return this._pendingDocument; + } + invalidateNonStallingEvaluations(error) { + if (!this._raceAgainstEvaluationStallingEventsPromises.size) + return; + for (const promise of this._raceAgainstEvaluationStallingEventsPromises) + promise.reject(error); + } + async raceAgainstEvaluationStallingEvents(cb) { + if (this._pendingDocument) + throw new EvaluationStalledError("Frame is currently attempting a navigation"); + if (this._page.browserContext.dialogManager.hasOpenDialogsForPage(this._page)) + throw new EvaluationStalledError("Open JavaScript dialog prevents evaluation"); + const promise = new ManualPromise(); + this._raceAgainstEvaluationStallingEventsPromises.add(promise); + try { + return await Promise.race([ + cb(), + promise + ]); + } finally { + this._raceAgainstEvaluationStallingEventsPromises.delete(promise); + } + } + nonStallingRawEvaluateInExistingMainContext(expression2) { + return this.raceAgainstEvaluationStallingEvents(() => { + const context = this.existingContext("main"); + if (!context) + throw new Error("Frame does not yet have a main execution context"); + return context.rawEvaluateJSON(expression2); + }); + } + nonStallingEvaluateInExistingContext(expression2, world) { + return this.raceAgainstEvaluationStallingEvents(() => { + const context = this._contextData.get(world)?.context; + if (!context) + throw new Error("Frame does not yet have the execution context"); + return context.evaluateExpression(expression2, { isFunction: false }); + }); + } + _recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle) { + let isNetworkIdle = this._firedNetworkIdleSelf; + for (const child of this._childFrames) { + child._recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle); + if (!child._firedLifecycleEvents.has("networkidle")) + isNetworkIdle = false; + } + if (isNetworkIdle && !this._firedLifecycleEvents.has("networkidle")) { + this._firedLifecycleEvents.add("networkidle"); + this.emit(_Frame.Events.AddLifecycle, "networkidle"); + if (this === this._page.mainFrame() && this._url !== "about:blank") + this.apiLog(` "networkidle" event fired`); + } + if (frameThatAllowsRemovingNetworkIdle !== this && this._firedLifecycleEvents.has("networkidle") && !isNetworkIdle) { + this._firedLifecycleEvents.delete("networkidle"); + this.emit(_Frame.Events.RemoveLifecycle, "networkidle"); + } + } + async raceNavigationAction(progress2, action) { + progress2.setAllowConcurrentOrNestedRaces(true); + const result2 = await progress2.race(LongStandingScope.raceMultiple([ + this._detachedScope, + this._page.openScope + ], action().catch((e) => { + if (e instanceof NavigationAbortedError && e.documentId) { + const data = this._redirectedNavigations.get(e.documentId); + if (data) { + progress2.log(`waiting for redirected navigation to "${data.url}"`); + return progress2.race(data.gotoPromise); + } + } + throw e; + }))); + progress2.setAllowConcurrentOrNestedRaces(false); + return result2; + } + redirectNavigation(url3, documentId, referer) { + const controller = new ProgressController(); + const data = { + url: url3, + gotoPromise: controller.run((progress2) => this.gotoImpl(progress2, url3, { referer }), 0) + }; + this._redirectedNavigations.set(documentId, data); + data.gotoPromise.finally(() => this._redirectedNavigations.delete(documentId)); + } + async goto(progress2, url3, options = {}) { + const constructedNavigationURL = constructURLBasedOnBaseURL(this._page.browserContext._options.baseURL, url3); + return this.raceNavigationAction(progress2, async () => this.gotoImpl(progress2, constructedNavigationURL, options)); + } + async gotoImpl(progress2, url3, options) { + const waitUntil = verifyLifecycle("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil); + progress2.log(`navigating to "${url3}", waiting until "${waitUntil}"`); + const headers = this._page.extraHTTPHeaders() || []; + const refererHeader = headers.find((h) => h.name.toLowerCase() === "referer"); + let referer = refererHeader ? refererHeader.value : void 0; + if (options.referer !== void 0) { + if (referer !== void 0 && referer !== options.referer) + throw new Error('"referer" is already specified as extra HTTP header'); + referer = options.referer; + } + url3 = helper.completeUserURL(url3); + const navigationEvents = []; + const collectNavigations = (arg2) => navigationEvents.push(arg2); + this.on(_Frame.Events.InternalNavigation, collectNavigations); + let navigateResult; + try { + navigateResult = await progress2.race(this._page.delegate.navigateFrame(this, url3, referer)); + } finally { + this.off(_Frame.Events.InternalNavigation, collectNavigations); + } + let event; + if (navigateResult.newDocumentId) { + const predicate = (event2) => { + return event2.newDocument && (event2.newDocument.documentId === navigateResult.newDocumentId || !event2.error); + }; + const events = navigationEvents.filter(predicate); + if (events.length) + event = events[0]; + else + event = await helper.waitForEvent(progress2, this, _Frame.Events.InternalNavigation, predicate).promise; + if (event.newDocument.documentId !== navigateResult.newDocumentId) { + throw new NavigationAbortedError(navigateResult.newDocumentId, `Navigation to "${url3}" is interrupted by another navigation to "${event.url}"`); + } + if (event.error) + throw event.error; + } else { + const predicate = (e) => !e.newDocument; + const events = navigationEvents.filter(predicate); + if (events.length) + event = events[0]; + else + event = await helper.waitForEvent(progress2, this, _Frame.Events.InternalNavigation, predicate).promise; + } + if (!this._firedLifecycleEvents.has(waitUntil)) + await helper.waitForEvent(progress2, this, _Frame.Events.AddLifecycle, (e) => e === waitUntil).promise; + const request2 = event.newDocument ? event.newDocument.request : void 0; + const response2 = request2 ? await request2._finalRequest().response(progress2) : null; + return response2; + } + async waitForNavigation(progress2, requiresNewDocument, options) { + const waitUntil = verifyLifecycle("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil); + progress2.log(`waiting for navigation until "${waitUntil}"`); + const navigationEvent = await helper.waitForEvent(progress2, this, _Frame.Events.InternalNavigation, (event) => { + if (event.error) + return true; + if (requiresNewDocument && !event.newDocument) + return false; + progress2.log(` navigated to "${this._url}"`); + return true; + }).promise; + if (navigationEvent.error) + throw navigationEvent.error; + if (!this._firedLifecycleEvents.has(waitUntil)) + await helper.waitForEvent(progress2, this, _Frame.Events.AddLifecycle, (e) => e === waitUntil).promise; + const request2 = navigationEvent.newDocument ? navigationEvent.newDocument.request : void 0; + return request2 ? request2._finalRequest().response(progress2) : null; + } + async waitForLoadState(progress2, state) { + const waitUntil = verifyLifecycle("state", state); + if (!this._firedLifecycleEvents.has(waitUntil)) + await helper.waitForEvent(progress2, this, _Frame.Events.AddLifecycle, (e) => e === waitUntil).promise; + } + async frameElement(progress2) { + return await progress2.race(this._page.delegate.getFrameElement(this)); + } + context(world) { + if (this._page.delegate.noUtilityWorld?.()) + world = "main"; + return this._contextData.get(world).contextPromise.then((contextOrDestroyedReason) => { + if (contextOrDestroyedReason instanceof ExecutionContext) + return contextOrDestroyedReason; + throw new Error(contextOrDestroyedReason.destroyedReason); + }); + } + mainContext() { + return this.context("main"); + } + existingContext(world) { + if (this._page.delegate.noUtilityWorld?.()) + world = "main"; + return this._contextData.get(world)?.context || null; + } + utilityContext() { + return this.context("utility"); + } + async evaluateExpression(progress2, expression2, options = {}, arg2) { + return await progress2.race(this._evaluateExpression(expression2, options, arg2)); + } + async _evaluateExpression(expression2, options = {}, arg2) { + const context = await this.context(options.world ?? "main"); + const value2 = await context.evaluateExpression(expression2, options, arg2); + return value2; + } + async evaluateExpressionHandle(progress2, expression2, options = {}, arg2) { + return await progress2.race(this._evaluateExpressionHandle(expression2, options, arg2)); + } + async _evaluateExpressionHandle(expression2, options = {}, arg2) { + const context = await this.context(options.world ?? "main"); + const value2 = await context.evaluateExpressionHandle(expression2, options, arg2); + return value2; + } + async querySelector(progress2, target) { + this.apiLog(` finding element using the selector "${target.selector}"`); + return progress2.race(this.selectors.query(target)); + } + async waitForSelector(progress2, target, performActionPreChecksAndLog, options) { + const { selector, scope } = target; + if (options.visibility) + throw new Error("options.visibility is not supported, did you mean options.state?"); + if (options.waitFor && options.waitFor !== "visible") + throw new Error("options.waitFor is not supported, did you mean options.state?"); + const { state = "visible" } = options; + if (!["attached", "detached", "visible", "hidden"].includes(state)) + throw new Error(`state: expected one of (attached|detached|visible|hidden)`); + if (performActionPreChecksAndLog) + progress2.log(`waiting for ${this._asLocator(selector)}${state === "attached" ? "" : " to be " + state}`); + const promise = this.retryWithProgressAndBackoff(progress2, async (progress3, continuePolling) => { + if (performActionPreChecksAndLog) + await this._page.performActionPreChecks(progress3); + if (scope && await progress3.race(scope.evaluateInUtility(([injected, node]) => node.isConnected, {})) !== true) + throw new NonRecoverableDOMError("Element is not attached to the DOM"); + const resolved = await progress3.race(this.selectors.callOnSelectorHandle(target, ({ injected, elements, frameVisible }) => { + const element4 = elements[0]; + const visible3 = element4 ? injected.elementState(element4, "visible", frameVisible).matches : false; + let log3 = ""; + if (elements.length > 1) + log3 = ` locator resolved to ${elements.length} elements. Proceeding with the first one: ${injected.previewNode(elements[0])}`; + else if (element4) + log3 = ` locator resolved to ${visible3 ? "visible" : "hidden"} ${injected.previewNode(element4)}`; + return { log: log3, element: element4, visible: visible3, attached: !!element4 }; + }, {})); + if (!resolved) { + if (state === "hidden" || state === "detached") + return null; + return continuePolling; + } + const result2 = resolved.result; + const { log: log2, visible: visible2, attached } = await progress3.race(result2.evaluate((r) => ({ log: r.log, visible: r.visible, attached: r.attached }))); + if (log2) + progress3.log(log2); + const success = { attached, detached: !attached, visible: visible2, hidden: !visible2 }[state]; + if (!success) { + result2.dispose(); + return continuePolling; + } + if (options.omitReturnValue) { + result2.dispose(); + return null; + } + const element3 = state === "attached" || state === "visible" ? await progress3.race(result2.evaluateHandle((r) => r.element)) : null; + result2.dispose(); + if (!element3) + return null; + if (options.__testHookBeforeAdoptNode) + await progress3.race(options.__testHookBeforeAdoptNode()); + try { + const mainContext = await progress3.race(element3._frame.mainContext()); + return await progress3.race(element3._adoptTo(mainContext)); + } catch (e) { + return continuePolling; + } + }); + return scope ? scope._context.raceAgainstContextDestroyed(promise) : promise; + } + async dispatchEvent(progress2, target, type3, eventInit = {}) { + await this._waitForFunctionOnSelector(progress2, target, (injectedScript, element3, data) => { + injectedScript.dispatchEvent(element3, data.type, data.eventInit); + return { result: void 0 }; + }, { type: type3, eventInit }, { mainWorld: true }); + } + async evalOnSelector(progress2, target, expression2, isFunction2, arg2) { + return progress2.race(this._evalOnSelector(target, expression2, isFunction2, arg2)); + } + async _evalOnSelector(target, expression2, isFunction2, arg2) { + const handle = await this.selectors.query(target); + if (!handle) + throw new Error(`Failed to find element matching selector "${target.selector}"`); + const result2 = await handle.internalEvaluateExpression(expression2, { isFunction: isFunction2 }, arg2); + handle.dispose(); + return result2; + } + async evalOnSelectorAll(progress2, selector, expression2, isFunction2, arg2, scope) { + return progress2.race(this._evalOnSelectorAll(selector, expression2, isFunction2, arg2, scope)); + } + async _evalOnSelectorAll(selector, expression2, isFunction2, arg2, scope) { + const arrayHandle = await this.selectors.queryArrayInMainWorld(selector, scope); + const result2 = await arrayHandle.internalEvaluateExpression(expression2, { isFunction: isFunction2 }, arg2); + arrayHandle.dispose(); + return result2; + } + async querySelectorAll(progress2, selector) { + return progress2.race(this.selectors.queryAll(selector)); + } + async queryCount(progress2, selector) { + try { + return await progress2.race(this.selectors.queryCount(selector)); + } catch (e) { + if (this.isNonRetriableError(e)) + throw e; + return 0; + } + } + async content(progress2, options) { + return progress2.race(this._content(options)); + } + async _content(options) { + try { + const context = await this.utilityContext(); + const injected = await context.injectedScript(); + return await injected.evaluate((injected2, includeShadow) => injected2.documentContent(includeShadow), !!options.includeShadow); + } catch (e) { + if (this.isNonRetriableError(e)) + throw e; + throw new Error(`Unable to retrieve content because the page is navigating and changing the content.`); + } + } + async setContent(progress2, html, options) { + const tag = `--playwright--set--content--${createGuid()}--`; + await this.raceNavigationAction(progress2, async () => { + const waitUntil = options.waitUntil === void 0 ? "load" : options.waitUntil; + progress2.log(`setting frame content, waiting until "${waitUntil}"`); + const context = await progress2.race(this.utilityContext()); + const tagPromise = new ManualPromise(); + this._page.frameManager._consoleMessageTags.set(tag, () => { + this._onClearLifecycle(); + tagPromise.resolve(); + }); + progress2.setAllowConcurrentOrNestedRaces(true); + const lifecyclePromise = progress2.race(tagPromise).then(() => this.waitForLoadState(progress2, waitUntil)); + const contentPromise = progress2.race(context.evaluate(({ html: html2, tag: tag2 }) => { + document.open(); + console.debug(tag2); + document.write(html2); + document.close(); + }, { html, tag })); + await Promise.all([contentPromise, lifecyclePromise]); + progress2.setAllowConcurrentOrNestedRaces(false); + return null; + }).finally(() => { + this._page.frameManager._consoleMessageTags.delete(tag); + }); + } + name() { + return this._name || ""; + } + url() { + return this._url; + } + origin() { + if (!this._url.startsWith("http")) + return; + return parseURL2(this._url)?.origin; + } + parentFrame() { + return this._parentFrame; + } + childFrames() { + return Array.from(this._childFrames); + } + async addScriptTag(progress2, params2) { + return await progress2.race(this._addScriptTag(params2)); + } + async _addScriptTag(params2) { + const { + url: url3 = null, + content = null, + type: type3 = "" + } = params2; + if (!url3 && !content) + throw new Error("Provide an object with a `url`, `path` or `content` property"); + const context = await this.mainContext(); + return this._raceWithCSPError(async () => { + if (url3 !== null) + return (await context.evaluateHandle(addScriptUrl, { url: url3, type: type3 })).asElement(); + const result2 = (await context.evaluateHandle(addScriptContent, { content, type: type3 })).asElement(); + if (this._page.delegate.cspErrorsAsynchronousForInlineScripts) + await context.evaluate(() => true); + return result2; + }); + async function addScriptUrl(params3) { + const script = document.createElement("script"); + script.src = params3.url; + if (params3.type) + script.type = params3.type; + const promise = new Promise((res, rej) => { + script.onload = res; + script.onerror = (e) => rej(typeof e === "string" ? new Error(e) : new Error(`Failed to load script at ${script.src}`)); + }); + document.head.appendChild(script); + await promise; + return script; + } + function addScriptContent(params3) { + const script = document.createElement("script"); + script.type = params3.type || "text/javascript"; + script.text = params3.content; + let error = null; + script.onerror = (e) => error = e; + document.head.appendChild(script); + if (error) + throw error; + return script; + } + } + async addStyleTag(progress2, params2) { + return await progress2.race(this._addStyleTag(params2)); + } + async _addStyleTag(params2) { + const { + url: url3 = null, + content = null + } = params2; + if (!url3 && !content) + throw new Error("Provide an object with a `url`, `path` or `content` property"); + const context = await this.mainContext(); + return this._raceWithCSPError(async () => { + if (url3 !== null) + return (await context.evaluateHandle(addStyleUrl, url3)).asElement(); + return (await context.evaluateHandle(addStyleContent, content)).asElement(); + }); + async function addStyleUrl(url4) { + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.href = url4; + const promise = new Promise((res, rej) => { + link.onload = res; + link.onerror = rej; + }); + document.head.appendChild(link); + await promise; + return link; + } + async function addStyleContent(content2) { + const style = document.createElement("style"); + style.type = "text/css"; + style.appendChild(document.createTextNode(content2)); + const promise = new Promise((res, rej) => { + style.onload = res; + style.onerror = rej; + }); + document.head.appendChild(style); + await promise; + return style; + } + } + async _raceWithCSPError(func) { + const listeners = []; + let result2; + let error; + let cspMessage; + const actionPromise = func().then((r) => result2 = r).catch((e) => error = e); + const errorPromise = new Promise((resolve) => { + listeners.push(eventsHelper.addEventListener(this._page.browserContext, BrowserContext.Events.Console, (message) => { + if (message.page() !== this._page || message.type() !== "error") + return; + if (message.text().includes("Content-Security-Policy") || message.text().includes("Content Security Policy")) { + cspMessage = message; + resolve(); + } + })); + }); + await Promise.race([actionPromise, errorPromise]); + eventsHelper.removeEventListeners(listeners); + if (cspMessage) + throw new Error(cspMessage.text()); + if (error) + throw error; + return result2; + } + async retryWithProgressAndBackoff(progress2, action) { + const backoffScale = [20, 50, 100, 100, 500]; + if (progress2.timeout) { + while (backoffScale.length && backoffScale[backoffScale.length - 1] > progress2.timeout / 5) + backoffScale.pop(); + } + return await this.retryWithProgressAndTimeouts(progress2, backoffScale, action); + } + async retryWithProgressAndTimeouts(progress2, timeouts, action) { + const continuePolling = /* @__PURE__ */ Symbol("continuePolling"); + timeouts = [0, ...timeouts]; + let timeoutIndex = 0; + while (true) { + const timeout = timeouts[Math.min(timeoutIndex++, timeouts.length - 1)]; + if (timeout) { + const actionPromise = new Promise((f) => setTimeout(f, timeout)); + await progress2.race(LongStandingScope.raceMultiple([ + this._page.openScope, + this._detachedScope + ], actionPromise)); + } + try { + const result2 = await action(progress2, continuePolling); + if (result2 === continuePolling) + continue; + return result2; + } catch (e) { + if (this.isNonRetriableError(e)) + throw e; + continue; + } + } + } + isNonRetriableError(e) { + if (isAbortError(e)) + return true; + if (isJavaScriptErrorInEvaluate(e) || isSessionClosedError(e)) + return true; + if (isNonRecoverableDOMError(e) || isInvalidSelectorError(e)) + return true; + if (this._isDetached()) + return true; + return false; + } + async _retryWithProgressIfNotConnected(progress2, target, options, action) { + progress2.log(`waiting for ${this._asLocator(target.selector)}`); + const performActionPreChecks = !options.skipActionPreChecks && !options.force; + const waitForFrameVisible = options.waitForFrameVisible && !options.force; + return this.retryWithProgressAndBackoff(progress2, async (progress3, continuePolling) => { + if (performActionPreChecks) + await this._page.performActionPreChecks(progress3); + const resolved = await progress3.race(this.selectors.callOnSelectorHandle({ ...target, markTargets: "all" }, ({ injected, elements }) => { + const element4 = elements[0]; + let log3 = ""; + if (elements.length > 1) + log3 = ` locator resolved to ${elements.length} elements. Proceeding with the first one: ${injected.previewNode(elements[0])}`; + else if (element4) + log3 = ` locator resolved to ${injected.previewNode(element4)}`; + const rect = element4?.getBoundingClientRect(); + return { log: log3, success: !!element4, element: element4, box: rect ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : void 0 }; + }, {})); + if (!resolved) + return continuePolling; + const result2 = resolved.result; + const { log: log2, success, box } = await progress3.race(result2.evaluate((r) => ({ log: r.log, success: r.success, box: r.box }))); + if (log2) + progress3.log(log2); + if (!success) { + result2.dispose(); + return continuePolling; + } + if (waitForFrameVisible && !resolved.frameVisible) { + progress3.log(" element is inside a hidden frame, retrying"); + result2.dispose(); + return continuePolling; + } + const element3 = await progress3.race(result2.evaluateHandle((r) => r.element)); + result2.dispose(); + try { + const result3 = await action(progress3, element3, box, resolved.frameVisible); + if (result3 === "error:notconnected") { + progress3.log("element was detached from the DOM, retrying"); + return continuePolling; + } + return result3; + } finally { + element3?.dispose(); + } + }); + } + async rafrafTimeoutScreenshotElementWithProgress(progress2, selector, timeout, options) { + return await this._retryWithProgressIfNotConnected(progress2, { selector, strict: true }, { waitForFrameVisible: true }, async (progress3, handle, box, frameVisible) => { + await handle._frame.rafrafTimeout(progress3, timeout); + return await this._page.screenshotter.screenshotElement(progress3, handle, options, frameVisible); + }); + } + async click(progress2, target, options) { + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._click(progress3, options, !options.noWaitAfter, frameVisible))); + } + async dblclick(progress2, target, options) { + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._dblclick(progress3, options, frameVisible))); + } + async dragAndDrop(progress2, source14, target, options) { + assertDone(await this._retryWithProgressIfNotConnected(progress2, source14, { force: options.force, waitForFrameVisible: true }, async (progress3, handle, box, frameVisible) => { + return handle._retryPointerAction(progress3, { + name: "move and down", + waitForEnabled: false, + waitAfter: "disabled", + perform: async (progress4, point) => { + await this._page.mouse.move(progress4, point.x, point.y); + await this._page.mouse.down(progress4); + } + }, { ...options, position: options.sourcePosition }, frameVisible); + })); + assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true, skipActionPreChecks: true }, async (progress3, handle, box, frameVisible) => { + return handle._retryPointerAction(progress3, { + name: "move and up", + waitForEnabled: false, + waitAfter: "disabled", + skipActionPreChecks: true, + perform: async (progress4, point) => { + await this._page.mouse.move(progress4, point.x, point.y, { steps: options.steps }); + await this._page.mouse.up(progress4); + } + }, { ...options, position: options.targetPosition }, frameVisible); + })); + } + async tap(progress2, target, options) { + if (!this._page.browserContext._options.hasTouch) + throw new Error("The page does not support tap. Use hasTouch context option to enable touch support."); + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._tap(progress3, options, frameVisible))); + } + async fill(progress2, target, value2, options) { + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._fill(progress3, value2, options, frameVisible, box))); + } + async focus(progress2, target) { + assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { waitForFrameVisible: false }, (progress3, handle) => handle._focus(progress3))); + } + async blur(progress2, target) { + assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { waitForFrameVisible: false }, (progress3, handle) => handle._blur(progress3))); + } + async resolveSelector(progress2, selector, options = {}) { + const element3 = await progress2.race(this.selectors.query({ selector, ...options })); + if (!element3) + throw new Error(`No element matching ${selector}`); + const generated = await progress2.race(element3.evaluateInUtility(async ([injected, node]) => { + return injected.generateSelectorSimple(node); + }, {})); + if (!generated) + throw new Error(`Unable to generate locator for ${selector}`); + let frame = element3._frame; + const result2 = [generated]; + while (frame?.parentFrame()) { + const frameElement = await frame.frameElement(progress2); + if (frameElement) { + const generated2 = await progress2.race(frameElement.evaluateInUtility(async ([injected, node]) => { + return injected.generateSelectorSimple(node); + }, {})); + frameElement.dispose(); + if (generated2 === "error:notconnected" || !generated2) + throw new Error(`Unable to generate locator for ${selector}`); + result2.push(generated2); + } + frame = frame.parentFrame(); + } + const resolvedSelector = result2.reverse().join(" >> internal:control=enter-frame >> "); + return { resolvedSelector }; + } + async textContent(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injected, element3) => ({ result: element3.textContent }), void 0); + return result2; + } + async innerText(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injectedScript, element3) => { + if (element3.namespaceURI !== "http://www.w3.org/1999/xhtml") + throw injectedScript.createStacklessError("Node is not an HTMLElement"); + return { result: element3.innerText }; + }, void 0); + return result2; + } + async innerHTML(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injected, element3) => ({ result: element3.innerHTML }), void 0); + return result2; + } + async getAttribute(progress2, target, name) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injected, element3, data) => ({ result: element3.getAttribute(data.name) }), { name }); + return result2; + } + async inputValue(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injectedScript, node) => { + const element3 = injectedScript.retarget(node, "follow-label"); + if (!element3 || element3.nodeName !== "INPUT" && element3.nodeName !== "TEXTAREA" && element3.nodeName !== "SELECT") + throw injectedScript.createStacklessError("Node is not an ,