aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Jarred Sumner <jarred@jarredsumner.com> 2021-06-17 11:14:20 -0700
committerGravatar Jarred Sumner <jarred@jarredsumner.com> 2021-06-17 11:14:20 -0700
commit4ca1e17778dc4a331da5a9a21f56e0e590c799ce (patch)
tree8bf708bb660b1ee46453027986c065ac7e8f2f26
parent6e2c6cd6ea1fbda73977f563fc7fbdede1438527 (diff)
downloadbun-4ca1e17778dc4a331da5a9a21f56e0e590c799ce.tar.gz
bun-4ca1e17778dc4a331da5a9a21f56e0e590c799ce.tar.zst
bun-4ca1e17778dc4a331da5a9a21f56e0e590c799ce.zip
CSS scanner works
-rw-r--r--.gitignore4
-rw-r--r--.vscode/launch.json7
-rw-r--r--build.zig16
-rw-r--r--outdir/index.css113
-rw-r--r--outdir/index.js2338
-rw-r--r--src/bundler.zig76
-rw-r--r--src/cli.zig10
-rw-r--r--src/css_scanner.zig986
-rw-r--r--src/darwin_c.zig4
-rw-r--r--src/env.zig21
-rw-r--r--src/feature_flags.zig36
-rw-r--r--src/fs.zig28
-rw-r--r--src/global.zig58
-rw-r--r--src/http.zig8
-rw-r--r--src/js_printer.zig6
-rw-r--r--src/linker.zig171
-rw-r--r--src/options.zig15
-rw-r--r--src/resolver/resolve_path.zig4
-rw-r--r--src/test/fixtures/me@2x.jpegbin0 -> 6829 bytes
-rw-r--r--src/test/fixtures/simple.css1205
-rw-r--r--src/test/fixtures/test-import.css3
21 files changed, 2076 insertions, 3033 deletions
diff --git a/.gitignore b/.gitignore
index ce44cb80f..701e36fdf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,4 +39,6 @@ out
esbuilddir
*.jsb
parceldist
-esbuilddir \ No newline at end of file
+esbuilddir
+outdir/
+outcss \ No newline at end of file
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 414818c10..8ed5db09e 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -17,7 +17,12 @@
"request": "launch",
"name": "Dev Launch",
"program": "${workspaceFolder}/build/debug/macos-x86_64/esdev",
- "args": ["optional-chain-polyfill.js", "--resolve=disable"],
+ "args": [
+ "./simple.css",
+ "--resolve=dev",
+ "--outdir=outcss",
+ "--public-url=https://localhost:9000/"
+ ],
"cwd": "${workspaceFolder}/src/test/fixtures",
"console": "internalConsole"
},
diff --git a/build.zig b/build.zig
index 82938b938..d9db8368b 100644
--- a/build.zig
+++ b/build.zig
@@ -4,7 +4,7 @@ const resolve_path = @import("./src/resolver/resolve_path.zig");
pub fn addPicoHTTP(step: *std.build.LibExeObjStep, dir: []const u8) void {
const picohttp = step.addPackage(.{
.name = "picohttp",
- .path = "src/deps/picohttp.zig",
+ .path = .{ .path = "src/deps/picohttp.zig" },
});
step.addObjectFile(
@@ -35,7 +35,7 @@ pub fn build(b: *std.build.Builder) void {
if (target.getOsTag() == .wasi) {
exe.enable_wasmtime = true;
exe = b.addExecutable("esdev", "src/main_wasi.zig");
- exe.is_dynamic = true;
+ exe.linkage = .dynamic;
exe.setOutputDir(output_dir);
} else if (target.getCpuArch().isWasm()) {
// exe = b.addExecutable(
@@ -60,15 +60,15 @@ pub fn build(b: *std.build.Builder) void {
lib.setOutputDir(output_dir);
lib.want_lto = true;
- b.install_path = lib.getOutputPath();
+ b.install_path = lib.getOutputSource().getPath(b);
- std.debug.print("Build: ./{s}\n", .{lib.getOutputPath()});
+ std.debug.print("Build: ./{s}\n", .{b.install_path});
b.default_step.dependOn(&lib.step);
b.verbose_link = true;
lib.setTarget(target);
lib.setBuildMode(mode);
- std.fs.deleteTreeAbsolute(std.fs.path.join(std.heap.page_allocator, &.{ cwd, lib.getOutputPath() }) catch unreachable) catch {};
+ std.fs.deleteTreeAbsolute(std.fs.path.join(std.heap.page_allocator, &.{ cwd, lib.getOutputSource().getPath(b) }) catch unreachable) catch {};
var install = b.getInstallStep();
lib.strip = false;
lib.install();
@@ -92,11 +92,11 @@ pub fn build(b: *std.build.Builder) void {
exe.addPackage(.{
.name = "clap",
- .path = "src/deps/zig-clap/clap.zig",
+ .path = .{ .path = "src/deps/zig-clap/clap.zig" },
});
exe.setOutputDir(output_dir);
- std.debug.print("Build: ./{s}\n", .{exe.getOutputPath()});
+
var walker = std.fs.walkPath(std.heap.page_allocator, cwd) catch unreachable;
if (std.builtin.is_test) {
while (walker.next() catch unreachable) |entry| {
@@ -141,4 +141,6 @@ pub fn build(b: *std.build.Builder) void {
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
+
+ std.debug.print("Build: ./{s}/{s}\n", .{ output_dir, "esdev" });
}
diff --git a/outdir/index.css b/outdir/index.css
deleted file mode 100644
index 7c27b2d24..000000000
--- a/outdir/index.css
+++ /dev/null
@@ -1,113 +0,0 @@
-/* src/api/demo/styles/Home.module.css */
-.container {
- min-height: 100vh;
- padding: 0 0.5rem;
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- height: 100vh;
-}
-.main {
- padding: 5rem 0;
- flex: 1;
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
-}
-.footer {
- width: 100%;
- height: 100px;
- border-top: 1px solid #eaeaea;
- display: flex;
- justify-content: center;
- align-items: center;
-}
-.footer a {
- display: flex;
- justify-content: center;
- align-items: center;
- flex-grow: 1;
-}
-.title a {
- color: #0070f3;
- text-decoration: none;
-}
-.title a:hover,
-.title a:focus,
-.title a:active {
- text-decoration: underline;
-}
-.title {
- margin: 0;
- line-height: 1.15;
- font-size: 4rem;
-}
-.title,
-.description {
- text-align: center;
-}
-.description {
- line-height: 1.5;
- font-size: 1.5rem;
-}
-.code {
- background: #fafafa;
- border-radius: 5px;
- padding: 0.75rem;
- font-size: 1.1rem;
- font-family:
- Menlo,
- Monaco,
- Lucida Console,
- Liberation Mono,
- DejaVu Sans Mono,
- Bitstream Vera Sans Mono,
- Courier New,
- monospace;
-}
-.grid {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-wrap: wrap;
- max-width: 800px;
- margin-top: 3rem;
-}
-.card {
- margin: 1rem;
- padding: 1.5rem;
- text-align: left;
- color: inherit;
- text-decoration: none;
- border: 1px solid #eaeaea;
- border-radius: 10px;
- transition: color 0.15s ease, border-color 0.15s ease;
- width: 45%;
-}
-.card:hover,
-.card:focus,
-.card:active {
- color: #0070f3;
- border-color: #0070f3;
-}
-.card h2 {
- margin: 0 0 1rem 0;
- font-size: 1.5rem;
-}
-.card p {
- margin: 0;
- font-size: 1.25rem;
- line-height: 1.5;
-}
-.logo {
- height: 1em;
- margin-left: 0.5rem;
-}
-@media (max-width: 600px) {
- .grid {
- width: 100%;
- flex-direction: column;
- }
-}
diff --git a/outdir/index.js b/outdir/index.js
deleted file mode 100644
index 43bfebf71..000000000
--- a/outdir/index.js
+++ /dev/null
@@ -1,2338 +0,0 @@
-(() => {
- var __create = Object.create;
- var __defProp = Object.defineProperty;
- var __getProtoOf = Object.getPrototypeOf;
- var __hasOwnProp = Object.prototype.hasOwnProperty;
- var __getOwnPropNames = Object.getOwnPropertyNames;
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
- var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
- var __commonJS = (cb, mod) => () => (mod || cb((mod = {exports: {}}).exports, mod), mod.exports);
- var __reExport = (target, module, desc) => {
- if (module && typeof module === "object" || typeof module === "function") {
- for (let key of __getOwnPropNames(module))
- if (!__hasOwnProp.call(target, key) && key !== "default")
- __defProp(target, key, {get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable});
- }
- return target;
- };
- var __toModule = (module) => {
- return __reExport(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? {get: () => module.default, enumerable: true} : {value: module, enumerable: true})), module);
- };
-
- // src/api/demo/node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js
- var require_object_assign = __commonJS((exports, module) => {
- "use strict";
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
- function toObject(val) {
- if (val === null || val === void 0) {
- throw new TypeError("Object.assign cannot be called with null or undefined");
- }
- return Object(val);
- }
- function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- }
- var test1 = new String("abc");
- test1[5] = "de";
- if (Object.getOwnPropertyNames(test1)[0] === "5") {
- return false;
- }
- var test2 = {};
- for (var i = 0; i < 10; i++) {
- test2["_" + String.fromCharCode(i)] = i;
- }
- var order2 = Object.getOwnPropertyNames(test2).map(function(n) {
- return test2[n];
- });
- if (order2.join("") !== "0123456789") {
- return false;
- }
- var test3 = {};
- "abcdefghijklmnopqrst".split("").forEach(function(letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
- return false;
- }
- return true;
- } catch (err) {
- return false;
- }
- }
- module.exports = shouldUseNative() ? Object.assign : function(target, source) {
- var from;
- var to = toObject(target);
- var symbols;
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
- return to;
- };
- });
-
- // src/api/demo/node_modules/.pnpm/react@17.0.2/node_modules/react/cjs/react.development.js
- var require_react_development = __commonJS((exports) => {
- "use strict";
- if (true) {
- (function() {
- "use strict";
- var _assign = require_object_assign();
- var ReactVersion = "17.0.2";
- var REACT_ELEMENT_TYPE = 60103;
- var REACT_PORTAL_TYPE = 60106;
- exports.Fragment = 60107;
- exports.StrictMode = 60108;
- exports.Profiler = 60114;
- var REACT_PROVIDER_TYPE = 60109;
- var REACT_CONTEXT_TYPE = 60110;
- var REACT_FORWARD_REF_TYPE = 60112;
- exports.Suspense = 60113;
- var REACT_SUSPENSE_LIST_TYPE = 60120;
- var REACT_MEMO_TYPE = 60115;
- var REACT_LAZY_TYPE = 60116;
- var REACT_BLOCK_TYPE = 60121;
- var REACT_SERVER_BLOCK_TYPE = 60122;
- var REACT_FUNDAMENTAL_TYPE = 60117;
- var REACT_SCOPE_TYPE = 60119;
- var REACT_OPAQUE_ID_TYPE = 60128;
- var REACT_DEBUG_TRACING_MODE_TYPE = 60129;
- var REACT_OFFSCREEN_TYPE = 60130;
- var REACT_LEGACY_HIDDEN_TYPE = 60131;
- if (typeof Symbol === "function" && Symbol.for) {
- var symbolFor = Symbol.for;
- REACT_ELEMENT_TYPE = symbolFor("react.element");
- REACT_PORTAL_TYPE = symbolFor("react.portal");
- exports.Fragment = symbolFor("react.fragment");
- exports.StrictMode = symbolFor("react.strict_mode");
- exports.Profiler = symbolFor("react.profiler");
- REACT_PROVIDER_TYPE = symbolFor("react.provider");
- REACT_CONTEXT_TYPE = symbolFor("react.context");
- REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref");
- exports.Suspense = symbolFor("react.suspense");
- REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list");
- REACT_MEMO_TYPE = symbolFor("react.memo");
- REACT_LAZY_TYPE = symbolFor("react.lazy");
- REACT_BLOCK_TYPE = symbolFor("react.block");
- REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block");
- REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental");
- REACT_SCOPE_TYPE = symbolFor("react.scope");
- REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id");
- REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode");
- REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen");
- REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden");
- }
- var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
- var FAUX_ITERATOR_SYMBOL = "@@iterator";
- function getIteratorFn(maybeIterable) {
- if (maybeIterable === null || typeof maybeIterable !== "object") {
- return null;
- }
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
- if (typeof maybeIterator === "function") {
- return maybeIterator;
- }
- return null;
- }
- var ReactCurrentDispatcher = {
- current: null
- };
- var ReactCurrentBatchConfig = {
- transition: 0
- };
- var ReactCurrentOwner = {
- current: null
- };
- var ReactDebugCurrentFrame = {};
- var currentExtraStackFrame = null;
- function setExtraStackFrame(stack) {
- {
- currentExtraStackFrame = stack;
- }
- }
- {
- ReactDebugCurrentFrame.setExtraStackFrame = function(stack) {
- {
- currentExtraStackFrame = stack;
- }
- };
- ReactDebugCurrentFrame.getCurrentStack = null;
- ReactDebugCurrentFrame.getStackAddendum = function() {
- var stack = "";
- if (currentExtraStackFrame) {
- stack += currentExtraStackFrame;
- }
- var impl = ReactDebugCurrentFrame.getCurrentStack;
- if (impl) {
- stack += impl() || "";
- }
- return stack;
- };
- }
- var IsSomeRendererActing = {
- current: false
- };
- var ReactSharedInternals = {
- ReactCurrentDispatcher,
- ReactCurrentBatchConfig,
- ReactCurrentOwner,
- IsSomeRendererActing,
- assign: _assign
- };
- {
- ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
- }
- function warn(format) {
- {
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
- printWarning("warn", format, args);
- }
- }
- function error(format) {
- {
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
- args[_key2 - 1] = arguments[_key2];
- }
- printWarning("error", format, args);
- }
- }
- function printWarning(level, format, args) {
- {
- var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
- var stack = ReactDebugCurrentFrame2.getStackAddendum();
- if (stack !== "") {
- format += "%s";
- args = args.concat([stack]);
- }
- var argsWithFormat = args.map(function(item) {
- return "" + item;
- });
- argsWithFormat.unshift("Warning: " + format);
- Function.prototype.apply.call(console[level], console, argsWithFormat);
- }
- }
- var didWarnStateUpdateForUnmountedComponent = {};
- function warnNoop(publicInstance, callerName) {
- {
- var _constructor = publicInstance.constructor;
- var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass";
- var warningKey = componentName + "." + callerName;
- if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
- return;
- }
- error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName);
- didWarnStateUpdateForUnmountedComponent[warningKey] = true;
- }
- }
- var ReactNoopUpdateQueue = {
- isMounted: function(publicInstance) {
- return false;
- },
- enqueueForceUpdate: function(publicInstance, callback, callerName) {
- warnNoop(publicInstance, "forceUpdate");
- },
- enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
- warnNoop(publicInstance, "replaceState");
- },
- enqueueSetState: function(publicInstance, partialState, callback, callerName) {
- warnNoop(publicInstance, "setState");
- }
- };
- var emptyObject = {};
- {
- Object.freeze(emptyObject);
- }
- function Component(props, context, updater) {
- this.props = props;
- this.context = context;
- this.refs = emptyObject;
- this.updater = updater || ReactNoopUpdateQueue;
- }
- Component.prototype.isReactComponent = {};
- Component.prototype.setState = function(partialState, callback) {
- if (!(typeof partialState === "object" || typeof partialState === "function" || partialState == null)) {
- {
- throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
- }
- }
- this.updater.enqueueSetState(this, partialState, callback, "setState");
- };
- Component.prototype.forceUpdate = function(callback) {
- this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
- };
- {
- var deprecatedAPIs = {
- isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],
- replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]
- };
- var defineDeprecationWarning = function(methodName, info) {
- Object.defineProperty(Component.prototype, methodName, {
- get: function() {
- warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
- return void 0;
- }
- });
- };
- for (var fnName in deprecatedAPIs) {
- if (deprecatedAPIs.hasOwnProperty(fnName)) {
- defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
- }
- }
- }
- function ComponentDummy() {
- }
- ComponentDummy.prototype = Component.prototype;
- function PureComponent(props, context, updater) {
- this.props = props;
- this.context = context;
- this.refs = emptyObject;
- this.updater = updater || ReactNoopUpdateQueue;
- }
- var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
- pureComponentPrototype.constructor = PureComponent;
- _assign(pureComponentPrototype, Component.prototype);
- pureComponentPrototype.isPureReactComponent = true;
- function createRef() {
- var refObject = {
- current: null
- };
- {
- Object.seal(refObject);
- }
- return refObject;
- }
- function getWrappedName(outerType, innerType, wrapperName) {
- var functionName = innerType.displayName || innerType.name || "";
- return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName);
- }
- function getContextName(type) {
- return type.displayName || "Context";
- }
- function getComponentName(type) {
- if (type == null) {
- return null;
- }
- {
- if (typeof type.tag === "number") {
- error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue.");
- }
- }
- if (typeof type === "function") {
- return type.displayName || type.name || null;
- }
- if (typeof type === "string") {
- return type;
- }
- switch (type) {
- case exports.Fragment:
- return "Fragment";
- case REACT_PORTAL_TYPE:
- return "Portal";
- case exports.Profiler:
- return "Profiler";
- case exports.StrictMode:
- return "StrictMode";
- case exports.Suspense:
- return "Suspense";
- case REACT_SUSPENSE_LIST_TYPE:
- return "SuspenseList";
- }
- if (typeof type === "object") {
- switch (type.$$typeof) {
- case REACT_CONTEXT_TYPE:
- var context = type;
- return getContextName(context) + ".Consumer";
- case REACT_PROVIDER_TYPE:
- var provider = type;
- return getContextName(provider._context) + ".Provider";
- case REACT_FORWARD_REF_TYPE:
- return getWrappedName(type, type.render, "ForwardRef");
- case REACT_MEMO_TYPE:
- return getComponentName(type.type);
- case REACT_BLOCK_TYPE:
- return getComponentName(type._render);
- case REACT_LAZY_TYPE: {
- var lazyComponent = type;
- var payload = lazyComponent._payload;
- var init = lazyComponent._init;
- try {
- return getComponentName(init(payload));
- } catch (x) {
- return null;
- }
- }
- }
- }
- return null;
- }
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var RESERVED_PROPS = {
- key: true,
- ref: true,
- __self: true,
- __source: true
- };
- var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
- {
- didWarnAboutStringRefs = {};
- }
- function hasValidRef(config) {
- {
- if (hasOwnProperty.call(config, "ref")) {
- var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
- if (getter && getter.isReactWarning) {
- return false;
- }
- }
- }
- return config.ref !== void 0;
- }
- function hasValidKey(config) {
- {
- if (hasOwnProperty.call(config, "key")) {
- var getter = Object.getOwnPropertyDescriptor(config, "key").get;
- if (getter && getter.isReactWarning) {
- return false;
- }
- }
- }
- return config.key !== void 0;
- }
- function defineKeyPropWarningGetter(props, displayName) {
- var warnAboutAccessingKey = function() {
- {
- if (!specialPropKeyWarningShown) {
- specialPropKeyWarningShown = true;
- error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
- }
- }
- };
- warnAboutAccessingKey.isReactWarning = true;
- Object.defineProperty(props, "key", {
- get: warnAboutAccessingKey,
- configurable: true
- });
- }
- function defineRefPropWarningGetter(props, displayName) {
- var warnAboutAccessingRef = function() {
- {
- if (!specialPropRefWarningShown) {
- specialPropRefWarningShown = true;
- error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
- }
- }
- };
- warnAboutAccessingRef.isReactWarning = true;
- Object.defineProperty(props, "ref", {
- get: warnAboutAccessingRef,
- configurable: true
- });
- }
- function warnIfStringRefCannotBeAutoConverted(config) {
- {
- if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
- var componentName = getComponentName(ReactCurrentOwner.current.type);
- if (!didWarnAboutStringRefs[componentName]) {
- error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
- didWarnAboutStringRefs[componentName] = true;
- }
- }
- }
- }
- var ReactElement = function(type, key, ref, self2, source, owner, props) {
- var element = {
- $$typeof: REACT_ELEMENT_TYPE,
- type,
- key,
- ref,
- props,
- _owner: owner
- };
- {
- element._store = {};
- Object.defineProperty(element._store, "validated", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: false
- });
- Object.defineProperty(element, "_self", {
- configurable: false,
- enumerable: false,
- writable: false,
- value: self2
- });
- Object.defineProperty(element, "_source", {
- configurable: false,
- enumerable: false,
- writable: false,
- value: source
- });
- if (Object.freeze) {
- Object.freeze(element.props);
- Object.freeze(element);
- }
- }
- return element;
- };
- function createElement(type, config, children) {
- var propName;
- var props = {};
- var key = null;
- var ref = null;
- var self2 = null;
- var source = null;
- if (config != null) {
- if (hasValidRef(config)) {
- ref = config.ref;
- {
- warnIfStringRefCannotBeAutoConverted(config);
- }
- }
- if (hasValidKey(config)) {
- key = "" + config.key;
- }
- self2 = config.__self === void 0 ? null : config.__self;
- source = config.__source === void 0 ? null : config.__source;
- for (propName in config) {
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
- props[propName] = config[propName];
- }
- }
- }
- var childrenLength = arguments.length - 2;
- if (childrenLength === 1) {
- props.children = children;
- } else if (childrenLength > 1) {
- var childArray = Array(childrenLength);
- for (var i = 0; i < childrenLength; i++) {
- childArray[i] = arguments[i + 2];
- }
- {
- if (Object.freeze) {
- Object.freeze(childArray);
- }
- }
- props.children = childArray;
- }
- if (type && type.defaultProps) {
- var defaultProps = type.defaultProps;
- for (propName in defaultProps) {
- if (props[propName] === void 0) {
- props[propName] = defaultProps[propName];
- }
- }
- }
- {
- if (key || ref) {
- var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
- if (key) {
- defineKeyPropWarningGetter(props, displayName);
- }
- if (ref) {
- defineRefPropWarningGetter(props, displayName);
- }
- }
- }
- return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props);
- }
- function cloneAndReplaceKey(oldElement, newKey) {
- var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
- return newElement;
- }
- function cloneElement(element, config, children) {
- if (!!(element === null || element === void 0)) {
- {
- throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
- }
- }
- var propName;
- var props = _assign({}, element.props);
- var key = element.key;
- var ref = element.ref;
- var self2 = element._self;
- var source = element._source;
- var owner = element._owner;
- if (config != null) {
- if (hasValidRef(config)) {
- ref = config.ref;
- owner = ReactCurrentOwner.current;
- }
- if (hasValidKey(config)) {
- key = "" + config.key;
- }
- var defaultProps;
- if (element.type && element.type.defaultProps) {
- defaultProps = element.type.defaultProps;
- }
- for (propName in config) {
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
- if (config[propName] === void 0 && defaultProps !== void 0) {
- props[propName] = defaultProps[propName];
- } else {
- props[propName] = config[propName];
- }
- }
- }
- }
- var childrenLength = arguments.length - 2;
- if (childrenLength === 1) {
- props.children = children;
- } else if (childrenLength > 1) {
- var childArray = Array(childrenLength);
- for (var i = 0; i < childrenLength; i++) {
- childArray[i] = arguments[i + 2];
- }
- props.children = childArray;
- }
- return ReactElement(element.type, key, ref, self2, source, owner, props);
- }
- function isValidElement(object) {
- return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
- }
- var SEPARATOR = ".";
- var SUBSEPARATOR = ":";
- function escape(key) {
- var escapeRegex = /[=:]/g;
- var escaperLookup = {
- "=": "=0",
- ":": "=2"
- };
- var escapedString = key.replace(escapeRegex, function(match) {
- return escaperLookup[match];
- });
- return "$" + escapedString;
- }
- var didWarnAboutMaps = false;
- var userProvidedKeyEscapeRegex = /\/+/g;
- function escapeUserProvidedKey(text) {
- return text.replace(userProvidedKeyEscapeRegex, "$&/");
- }
- function getElementKey(element, index) {
- if (typeof element === "object" && element !== null && element.key != null) {
- return escape("" + element.key);
- }
- return index.toString(36);
- }
- function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
- var type = typeof children;
- if (type === "undefined" || type === "boolean") {
- children = null;
- }
- var invokeCallback = false;
- if (children === null) {
- invokeCallback = true;
- } else {
- switch (type) {
- case "string":
- case "number":
- invokeCallback = true;
- break;
- case "object":
- switch (children.$$typeof) {
- case REACT_ELEMENT_TYPE:
- case REACT_PORTAL_TYPE:
- invokeCallback = true;
- }
- }
- }
- if (invokeCallback) {
- var _child = children;
- var mappedChild = callback(_child);
- var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
- if (Array.isArray(mappedChild)) {
- var escapedChildKey = "";
- if (childKey != null) {
- escapedChildKey = escapeUserProvidedKey(childKey) + "/";
- }
- mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) {
- return c;
- });
- } else if (mappedChild != null) {
- if (isValidElement(mappedChild)) {
- mappedChild = cloneAndReplaceKey(mappedChild, escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey);
- }
- array.push(mappedChild);
- }
- return 1;
- }
- var child;
- var nextName;
- var subtreeCount = 0;
- var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR;
- if (Array.isArray(children)) {
- for (var i = 0; i < children.length; i++) {
- child = children[i];
- nextName = nextNamePrefix + getElementKey(child, i);
- subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
- }
- } else {
- var iteratorFn = getIteratorFn(children);
- if (typeof iteratorFn === "function") {
- var iterableChildren = children;
- {
- if (iteratorFn === iterableChildren.entries) {
- if (!didWarnAboutMaps) {
- warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead.");
- }
- didWarnAboutMaps = true;
- }
- }
- var iterator = iteratorFn.call(iterableChildren);
- var step;
- var ii = 0;
- while (!(step = iterator.next()).done) {
- child = step.value;
- nextName = nextNamePrefix + getElementKey(child, ii++);
- subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
- }
- } else if (type === "object") {
- var childrenString = "" + children;
- {
- {
- throw Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead.");
- }
- }
- }
- }
- return subtreeCount;
- }
- function mapChildren(children, func, context) {
- if (children == null) {
- return children;
- }
- var result = [];
- var count = 0;
- mapIntoArray(children, result, "", "", function(child) {
- return func.call(context, child, count++);
- });
- return result;
- }
- function countChildren(children) {
- var n = 0;
- mapChildren(children, function() {
- n++;
- });
- return n;
- }
- function forEachChildren(children, forEachFunc, forEachContext) {
- mapChildren(children, function() {
- forEachFunc.apply(this, arguments);
- }, forEachContext);
- }
- function toArray(children) {
- return mapChildren(children, function(child) {
- return child;
- }) || [];
- }
- function onlyChild(children) {
- if (!isValidElement(children)) {
- {
- throw Error("React.Children.only expected to receive a single React element child.");
- }
- }
- return children;
- }
- function createContext(defaultValue, calculateChangedBits) {
- if (calculateChangedBits === void 0) {
- calculateChangedBits = null;
- } else {
- {
- if (calculateChangedBits !== null && typeof calculateChangedBits !== "function") {
- error("createContext: Expected the optional second argument to be a function. Instead received: %s", calculateChangedBits);
- }
- }
- }
- var context = {
- $$typeof: REACT_CONTEXT_TYPE,
- _calculateChangedBits: calculateChangedBits,
- _currentValue: defaultValue,
- _currentValue2: defaultValue,
- _threadCount: 0,
- Provider: null,
- Consumer: null
- };
- context.Provider = {
- $$typeof: REACT_PROVIDER_TYPE,
- _context: context
- };
- var hasWarnedAboutUsingNestedContextConsumers = false;
- var hasWarnedAboutUsingConsumerProvider = false;
- var hasWarnedAboutDisplayNameOnConsumer = false;
- {
- var Consumer = {
- $$typeof: REACT_CONTEXT_TYPE,
- _context: context,
- _calculateChangedBits: context._calculateChangedBits
- };
- Object.defineProperties(Consumer, {
- Provider: {
- get: function() {
- if (!hasWarnedAboutUsingConsumerProvider) {
- hasWarnedAboutUsingConsumerProvider = true;
- error("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?");
- }
- return context.Provider;
- },
- set: function(_Provider) {
- context.Provider = _Provider;
- }
- },
- _currentValue: {
- get: function() {
- return context._currentValue;
- },
- set: function(_currentValue) {
- context._currentValue = _currentValue;
- }
- },
- _currentValue2: {
- get: function() {
- return context._currentValue2;
- },
- set: function(_currentValue2) {
- context._currentValue2 = _currentValue2;
- }
- },
- _threadCount: {
- get: function() {
- return context._threadCount;
- },
- set: function(_threadCount) {
- context._threadCount = _threadCount;
- }
- },
- Consumer: {
- get: function() {
- if (!hasWarnedAboutUsingNestedContextConsumers) {
- hasWarnedAboutUsingNestedContextConsumers = true;
- error("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?");
- }
- return context.Consumer;
- }
- },
- displayName: {
- get: function() {
- return context.displayName;
- },
- set: function(displayName) {
- if (!hasWarnedAboutDisplayNameOnConsumer) {
- warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName);
- hasWarnedAboutDisplayNameOnConsumer = true;
- }
- }
- }
- });
- context.Consumer = Consumer;
- }
- {
- context._currentRenderer = null;
- context._currentRenderer2 = null;
- }
- return context;
- }
- var Uninitialized = -1;
- var Pending = 0;
- var Resolved = 1;
- var Rejected = 2;
- function lazyInitializer(payload) {
- if (payload._status === Uninitialized) {
- var ctor = payload._result;
- var thenable = ctor();
- var pending = payload;
- pending._status = Pending;
- pending._result = thenable;
- thenable.then(function(moduleObject) {
- if (payload._status === Pending) {
- var defaultExport = moduleObject.default;
- {
- if (defaultExport === void 0) {
- error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
- }
- }
- var resolved = payload;
- resolved._status = Resolved;
- resolved._result = defaultExport;
- }
- }, function(error2) {
- if (payload._status === Pending) {
- var rejected = payload;
- rejected._status = Rejected;
- rejected._result = error2;
- }
- });
- }
- if (payload._status === Resolved) {
- return payload._result;
- } else {
- throw payload._result;
- }
- }
- function lazy(ctor) {
- var payload = {
- _status: -1,
- _result: ctor
- };
- var lazyType = {
- $$typeof: REACT_LAZY_TYPE,
- _payload: payload,
- _init: lazyInitializer
- };
- {
- var defaultProps;
- var propTypes;
- Object.defineProperties(lazyType, {
- defaultProps: {
- configurable: true,
- get: function() {
- return defaultProps;
- },
- set: function(newDefaultProps) {
- error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
- defaultProps = newDefaultProps;
- Object.defineProperty(lazyType, "defaultProps", {
- enumerable: true
- });
- }
- },
- propTypes: {
- configurable: true,
- get: function() {
- return propTypes;
- },
- set: function(newPropTypes) {
- error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
- propTypes = newPropTypes;
- Object.defineProperty(lazyType, "propTypes", {
- enumerable: true
- });
- }
- }
- });
- }
- return lazyType;
- }
- function forwardRef(render) {
- {
- if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
- error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).");
- } else if (typeof render !== "function") {
- error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render);
- } else {
- if (render.length !== 0 && render.length !== 2) {
- error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
- }
- }
- if (render != null) {
- if (render.defaultProps != null || render.propTypes != null) {
- error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");
- }
- }
- }
- var elementType = {
- $$typeof: REACT_FORWARD_REF_TYPE,
- render
- };
- {
- var ownName;
- Object.defineProperty(elementType, "displayName", {
- enumerable: false,
- configurable: true,
- get: function() {
- return ownName;
- },
- set: function(name) {
- ownName = name;
- if (render.displayName == null) {
- render.displayName = name;
- }
- }
- });
- }
- return elementType;
- }
- var enableScopeAPI = false;
- function isValidElementType(type) {
- if (typeof type === "string" || typeof type === "function") {
- return true;
- }
- if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI) {
- return true;
- }
- if (typeof type === "object" && type !== null) {
- if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) {
- return true;
- }
- }
- return false;
- }
- function memo(type, compare) {
- {
- if (!isValidElementType(type)) {
- error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type);
- }
- }
- var elementType = {
- $$typeof: REACT_MEMO_TYPE,
- type,
- compare: compare === void 0 ? null : compare
- };
- {
- var ownName;
- Object.defineProperty(elementType, "displayName", {
- enumerable: false,
- configurable: true,
- get: function() {
- return ownName;
- },
- set: function(name) {
- ownName = name;
- if (type.displayName == null) {
- type.displayName = name;
- }
- }
- });
- }
- return elementType;
- }
- function resolveDispatcher() {
- var dispatcher = ReactCurrentDispatcher.current;
- if (!(dispatcher !== null)) {
- {
- throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
- }
- }
- return dispatcher;
- }
- function useContext(Context, unstable_observedBits) {
- var dispatcher = resolveDispatcher();
- {
- if (unstable_observedBits !== void 0) {
- error("useContext() second argument is reserved for future use in React. Passing it is not supported. You passed: %s.%s", unstable_observedBits, typeof unstable_observedBits === "number" && Array.isArray(arguments[2]) ? "\n\nDid you call array.map(useContext)? Calling Hooks inside a loop is not supported. Learn more at https://reactjs.org/link/rules-of-hooks" : "");
- }
- if (Context._context !== void 0) {
- var realContext = Context._context;
- if (realContext.Consumer === Context) {
- error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?");
- } else if (realContext.Provider === Context) {
- error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?");
- }
- }
- }
- return dispatcher.useContext(Context, unstable_observedBits);
- }
- function useState(initialState) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useState(initialState);
- }
- function useReducer(reducer, initialArg, init) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useReducer(reducer, initialArg, init);
- }
- function useRef(initialValue) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useRef(initialValue);
- }
- function useEffect(create, deps) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useEffect(create, deps);
- }
- function useLayoutEffect(create, deps) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useLayoutEffect(create, deps);
- }
- function useCallback(callback, deps) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useCallback(callback, deps);
- }
- function useMemo(create, deps) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useMemo(create, deps);
- }
- function useImperativeHandle(ref, create, deps) {
- var dispatcher = resolveDispatcher();
- return dispatcher.useImperativeHandle(ref, create, deps);
- }
- function useDebugValue(value, formatterFn) {
- {
- var dispatcher = resolveDispatcher();
- return dispatcher.useDebugValue(value, formatterFn);
- }
- }
- var disabledDepth = 0;
- var prevLog;
- var prevInfo;
- var prevWarn;
- var prevError;
- var prevGroup;
- var prevGroupCollapsed;
- var prevGroupEnd;
- function disabledLog() {
- }
- disabledLog.__reactDisabledLog = true;
- function disableLogs() {
- {
- if (disabledDepth === 0) {
- prevLog = console.log;
- prevInfo = console.info;
- prevWarn = console.warn;
- prevError = console.error;
- prevGroup = console.group;
- prevGroupCollapsed = console.groupCollapsed;
- prevGroupEnd = console.groupEnd;
- var props = {
- configurable: true,
- enumerable: true,
- value: disabledLog,
- writable: true
- };
- Object.defineProperties(console, {
- info: props,
- log: props,
- warn: props,
- error: props,
- group: props,
- groupCollapsed: props,
- groupEnd: props
- });
- }
- disabledDepth++;
- }
- }
- function reenableLogs() {
- {
- disabledDepth--;
- if (disabledDepth === 0) {
- var props = {
- configurable: true,
- enumerable: true,
- writable: true
- };
- Object.defineProperties(console, {
- log: _assign({}, props, {
- value: prevLog
- }),
- info: _assign({}, props, {
- value: prevInfo
- }),
- warn: _assign({}, props, {
- value: prevWarn
- }),
- error: _assign({}, props, {
- value: prevError
- }),
- group: _assign({}, props, {
- value: prevGroup
- }),
- groupCollapsed: _assign({}, props, {
- value: prevGroupCollapsed
- }),
- groupEnd: _assign({}, props, {
- value: prevGroupEnd
- })
- });
- }
- if (disabledDepth < 0) {
- error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
- }
- }
- }
- var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
- var prefix;
- function describeBuiltInComponentFrame(name, source, ownerFn) {
- {
- if (prefix === void 0) {
- try {
- throw Error();
- } catch (x) {
- var match = x.stack.trim().match(/\n( *(at )?)/);
- prefix = match && match[1] || "";
- }
- }
- return "\n" + prefix + name;
- }
- }
- var reentry = false;
- var componentFrameCache;
- {
- var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
- componentFrameCache = new PossiblyWeakMap();
- }
- function describeNativeComponentFrame(fn, construct) {
- if (!fn || reentry) {
- return "";
- }
- {
- var frame = componentFrameCache.get(fn);
- if (frame !== void 0) {
- return frame;
- }
- }
- var control;
- reentry = true;
- var previousPrepareStackTrace = Error.prepareStackTrace;
- Error.prepareStackTrace = void 0;
- var previousDispatcher;
- {
- previousDispatcher = ReactCurrentDispatcher$1.current;
- ReactCurrentDispatcher$1.current = null;
- disableLogs();
- }
- try {
- if (construct) {
- var Fake = function() {
- throw Error();
- };
- Object.defineProperty(Fake.prototype, "props", {
- set: function() {
- throw Error();
- }
- });
- if (typeof Reflect === "object" && Reflect.construct) {
- try {
- Reflect.construct(Fake, []);
- } catch (x) {
- control = x;
- }
- Reflect.construct(fn, [], Fake);
- } else {
- try {
- Fake.call();
- } catch (x) {
- control = x;
- }
- fn.call(Fake.prototype);
- }
- } else {
- try {
- throw Error();
- } catch (x) {
- control = x;
- }
- fn();
- }
- } catch (sample) {
- if (sample && control && typeof sample.stack === "string") {
- var sampleLines = sample.stack.split("\n");
- var controlLines = control.stack.split("\n");
- var s = sampleLines.length - 1;
- var c = controlLines.length - 1;
- while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
- c--;
- }
- for (; s >= 1 && c >= 0; s--, c--) {
- if (sampleLines[s] !== controlLines[c]) {
- if (s !== 1 || c !== 1) {
- do {
- s--;
- c--;
- if (c < 0 || sampleLines[s] !== controlLines[c]) {
- var _frame = "\n" + sampleLines[s].replace(" at new ", " at ");
- {
- if (typeof fn === "function") {
- componentFrameCache.set(fn, _frame);
- }
- }
- return _frame;
- }
- } while (s >= 1 && c >= 0);
- }
- break;
- }
- }
- }
- } finally {
- reentry = false;
- {
- ReactCurrentDispatcher$1.current = previousDispatcher;
- reenableLogs();
- }
- Error.prepareStackTrace = previousPrepareStackTrace;
- }
- var name = fn ? fn.displayName || fn.name : "";
- var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
- {
- if (typeof fn === "function") {
- componentFrameCache.set(fn, syntheticFrame);
- }
- }
- return syntheticFrame;
- }
- function describeFunctionComponentFrame(fn, source, ownerFn) {
- {
- return describeNativeComponentFrame(fn, false);
- }
- }
- function shouldConstruct(Component2) {
- var prototype = Component2.prototype;
- return !!(prototype && prototype.isReactComponent);
- }
- function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
- if (type == null) {
- return "";
- }
- if (typeof type === "function") {
- {
- return describeNativeComponentFrame(type, shouldConstruct(type));
- }
- }
- if (typeof type === "string") {
- return describeBuiltInComponentFrame(type);
- }
- switch (type) {
- case exports.Suspense:
- return describeBuiltInComponentFrame("Suspense");
- case REACT_SUSPENSE_LIST_TYPE:
- return describeBuiltInComponentFrame("SuspenseList");
- }
- if (typeof type === "object") {
- switch (type.$$typeof) {
- case REACT_FORWARD_REF_TYPE:
- return describeFunctionComponentFrame(type.render);
- case REACT_MEMO_TYPE:
- return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
- case REACT_BLOCK_TYPE:
- return describeFunctionComponentFrame(type._render);
- case REACT_LAZY_TYPE: {
- var lazyComponent = type;
- var payload = lazyComponent._payload;
- var init = lazyComponent._init;
- try {
- return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
- } catch (x) {
- }
- }
- }
- }
- return "";
- }
- var loggedTypeFailures = {};
- var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
- function setCurrentlyValidatingElement(element) {
- {
- if (element) {
- var owner = element._owner;
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
- ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
- } else {
- ReactDebugCurrentFrame$1.setExtraStackFrame(null);
- }
- }
- }
- function checkPropTypes(typeSpecs, values, location, componentName, element) {
- {
- var has = Function.call.bind(Object.prototype.hasOwnProperty);
- for (var typeSpecName in typeSpecs) {
- if (has(typeSpecs, typeSpecName)) {
- var error$1 = void 0;
- try {
- if (typeof typeSpecs[typeSpecName] !== "function") {
- var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
- err.name = "Invariant Violation";
- throw err;
- }
- error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
- } catch (ex) {
- error$1 = ex;
- }
- if (error$1 && !(error$1 instanceof Error)) {
- setCurrentlyValidatingElement(element);
- error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
- setCurrentlyValidatingElement(null);
- }
- if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
- loggedTypeFailures[error$1.message] = true;
- setCurrentlyValidatingElement(element);
- error("Failed %s type: %s", location, error$1.message);
- setCurrentlyValidatingElement(null);
- }
- }
- }
- }
- }
- function setCurrentlyValidatingElement$1(element) {
- {
- if (element) {
- var owner = element._owner;
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
- setExtraStackFrame(stack);
- } else {
- setExtraStackFrame(null);
- }
- }
- }
- var propTypesMisspellWarningShown;
- {
- propTypesMisspellWarningShown = false;
- }
- function getDeclarationErrorAddendum() {
- if (ReactCurrentOwner.current) {
- var name = getComponentName(ReactCurrentOwner.current.type);
- if (name) {
- return "\n\nCheck the render method of `" + name + "`.";
- }
- }
- return "";
- }
- function getSourceInfoErrorAddendum(source) {
- if (source !== void 0) {
- var fileName = source.fileName.replace(/^.*[\\\/]/, "");
- var lineNumber = source.lineNumber;
- return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
- }
- return "";
- }
- function getSourceInfoErrorAddendumForProps(elementProps) {
- if (elementProps !== null && elementProps !== void 0) {
- return getSourceInfoErrorAddendum(elementProps.__source);
- }
- return "";
- }
- var ownerHasKeyUseWarning = {};
- function getCurrentComponentErrorInfo(parentType) {
- var info = getDeclarationErrorAddendum();
- if (!info) {
- var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
- if (parentName) {
- info = "\n\nCheck the top-level render call using <" + parentName + ">.";
- }
- }
- return info;
- }
- function validateExplicitKey(element, parentType) {
- if (!element._store || element._store.validated || element.key != null) {
- return;
- }
- element._store.validated = true;
- var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
- if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
- return;
- }
- ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
- var childOwner = "";
- if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
- childOwner = " It was passed a child from " + getComponentName(element._owner.type) + ".";
- }
- {
- setCurrentlyValidatingElement$1(element);
- error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
- setCurrentlyValidatingElement$1(null);
- }
- }
- function validateChildKeys(node, parentType) {
- if (typeof node !== "object") {
- return;
- }
- if (Array.isArray(node)) {
- for (var i = 0; i < node.length; i++) {
- var child = node[i];
- if (isValidElement(child)) {
- validateExplicitKey(child, parentType);
- }
- }
- } else if (isValidElement(node)) {
- if (node._store) {
- node._store.validated = true;
- }
- } else if (node) {
- var iteratorFn = getIteratorFn(node);
- if (typeof iteratorFn === "function") {
- if (iteratorFn !== node.entries) {
- var iterator = iteratorFn.call(node);
- var step;
- while (!(step = iterator.next()).done) {
- if (isValidElement(step.value)) {
- validateExplicitKey(step.value, parentType);
- }
- }
- }
- }
- }
- }
- function validatePropTypes(element) {
- {
- var type = element.type;
- if (type === null || type === void 0 || typeof type === "string") {
- return;
- }
- var propTypes;
- if (typeof type === "function") {
- propTypes = type.propTypes;
- } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) {
- propTypes = type.propTypes;
- } else {
- return;
- }
- if (propTypes) {
- var name = getComponentName(type);
- checkPropTypes(propTypes, element.props, "prop", name, element);
- } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
- propTypesMisspellWarningShown = true;
- var _name = getComponentName(type);
- error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
- }
- if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
- error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
- }
- }
- }
- function validateFragmentProps(fragment) {
- {
- var keys = Object.keys(fragment.props);
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- if (key !== "children" && key !== "key") {
- setCurrentlyValidatingElement$1(fragment);
- error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
- setCurrentlyValidatingElement$1(null);
- break;
- }
- }
- if (fragment.ref !== null) {
- setCurrentlyValidatingElement$1(fragment);
- error("Invalid attribute `ref` supplied to `React.Fragment`.");
- setCurrentlyValidatingElement$1(null);
- }
- }
- }
- function createElementWithValidation(type, props, children) {
- var validType = isValidElementType(type);
- if (!validType) {
- var info = "";
- if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
- info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
- }
- var sourceInfo = getSourceInfoErrorAddendumForProps(props);
- if (sourceInfo) {
- info += sourceInfo;
- } else {
- info += getDeclarationErrorAddendum();
- }
- var typeString;
- if (type === null) {
- typeString = "null";
- } else if (Array.isArray(type)) {
- typeString = "array";
- } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) {
- typeString = "<" + (getComponentName(type.type) || "Unknown") + " />";
- info = " Did you accidentally export a JSX literal instead of a component?";
- } else {
- typeString = typeof type;
- }
- {
- error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
- }
- }
- var element = createElement.apply(this, arguments);
- if (element == null) {
- return element;
- }
- if (validType) {
- for (var i = 2; i < arguments.length; i++) {
- validateChildKeys(arguments[i], type);
- }
- }
- if (type === exports.Fragment) {
- validateFragmentProps(element);
- } else {
- validatePropTypes(element);
- }
- return element;
- }
- var didWarnAboutDeprecatedCreateFactory = false;
- function createFactoryWithValidation(type) {
- var validatedFactory = createElementWithValidation.bind(null, type);
- validatedFactory.type = type;
- {
- if (!didWarnAboutDeprecatedCreateFactory) {
- didWarnAboutDeprecatedCreateFactory = true;
- warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.");
- }
- Object.defineProperty(validatedFactory, "type", {
- enumerable: false,
- get: function() {
- warn("Factory.type is deprecated. Access the class directly before passing it to createFactory.");
- Object.defineProperty(this, "type", {
- value: type
- });
- return type;
- }
- });
- }
- return validatedFactory;
- }
- function cloneElementWithValidation(element, props, children) {
- var newElement = cloneElement.apply(this, arguments);
- for (var i = 2; i < arguments.length; i++) {
- validateChildKeys(arguments[i], newElement.type);
- }
- validatePropTypes(newElement);
- return newElement;
- }
- {
- try {
- var frozenObject = Object.freeze({});
- new Map([[frozenObject, null]]);
- new Set([frozenObject]);
- } catch (e) {
- }
- }
- var createElement$1 = createElementWithValidation;
- var cloneElement$1 = cloneElementWithValidation;
- var createFactory = createFactoryWithValidation;
- var Children = {
- map: mapChildren,
- forEach: forEachChildren,
- count: countChildren,
- toArray,
- only: onlyChild
- };
- exports.Children = Children;
- exports.Component = Component;
- exports.PureComponent = PureComponent;
- exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
- exports.cloneElement = cloneElement$1;
- exports.createContext = createContext;
- exports.createElement = createElement$1;
- exports.createFactory = createFactory;
- exports.createRef = createRef;
- exports.forwardRef = forwardRef;
- exports.isValidElement = isValidElement;
- exports.lazy = lazy;
- exports.memo = memo;
- exports.useCallback = useCallback;
- exports.useContext = useContext;
- exports.useDebugValue = useDebugValue;
- exports.useEffect = useEffect;
- exports.useImperativeHandle = useImperativeHandle;
- exports.useLayoutEffect = useLayoutEffect;
- exports.useMemo = useMemo;
- exports.useReducer = useReducer;
- exports.useRef = useRef;
- exports.useState = useState;
- exports.version = ReactVersion;
- })();
- }
- });
-
- // src/api/demo/node_modules/.pnpm/react@17.0.2/node_modules/react/index.js
- var require_react = __commonJS((exports, module) => {
- "use strict";
- if (false) {
- module.exports = null;
- } else {
- module.exports = require_react_development();
- }
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/next-server/lib/side-effect.js
- var require_side_effect = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.default = void 0;
- var _react = require_react();
- var isServer = typeof window === "undefined";
- var _default2 = class extends _react.Component {
- constructor(props) {
- super(props);
- this._hasHeadManager = void 0;
- this.emitChange = () => {
- if (this._hasHeadManager) {
- this.props.headManager.updateHead(this.props.reduceComponentsToState([...this.props.headManager.mountedInstances], this.props));
- }
- };
- this._hasHeadManager = this.props.headManager && this.props.headManager.mountedInstances;
- if (isServer && this._hasHeadManager) {
- this.props.headManager.mountedInstances.add(this);
- this.emitChange();
- }
- }
- componentDidMount() {
- if (this._hasHeadManager) {
- this.props.headManager.mountedInstances.add(this);
- }
- this.emitChange();
- }
- componentDidUpdate() {
- this.emitChange();
- }
- componentWillUnmount() {
- if (this._hasHeadManager) {
- this.props.headManager.mountedInstances.delete(this);
- }
- this.emitChange();
- }
- render() {
- return null;
- }
- };
- exports.default = _default2;
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/next-server/lib/amp-context.js
- var require_amp_context = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.AmpStateContext = void 0;
- var _react = _interopRequireDefault(require_react());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {default: obj};
- }
- var AmpStateContext = /* @__PURE__ */ _react.default.createContext({});
- exports.AmpStateContext = AmpStateContext;
- if (true) {
- AmpStateContext.displayName = "AmpStateContext";
- }
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/next-server/lib/head-manager-context.js
- var require_head_manager_context = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.HeadManagerContext = void 0;
- var _react = _interopRequireDefault(require_react());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {default: obj};
- }
- var HeadManagerContext = /* @__PURE__ */ _react.default.createContext({});
- exports.HeadManagerContext = HeadManagerContext;
- if (true) {
- HeadManagerContext.displayName = "HeadManagerContext";
- }
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/next-server/lib/amp.js
- var require_amp = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.isInAmpMode = isInAmpMode;
- exports.useAmp = useAmp;
- var _react = _interopRequireDefault(require_react());
- var _ampContext = require_amp_context();
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {default: obj};
- }
- function isInAmpMode({ampFirst = false, hybrid = false, hasQuery = false} = {}) {
- return ampFirst || hybrid && hasQuery;
- }
- function useAmp() {
- return isInAmpMode(_react.default.useContext(_ampContext.AmpStateContext));
- }
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/next-server/lib/head.js
- var require_head = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.defaultHead = defaultHead;
- exports.default = void 0;
- var _react = _interopRequireWildcard(require_react());
- var _sideEffect = _interopRequireDefault(require_side_effect());
- var _ampContext = require_amp_context();
- var _headManagerContext = require_head_manager_context();
- var _amp = require_amp();
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {default: obj};
- }
- function _getRequireWildcardCache() {
- if (typeof WeakMap !== "function")
- return null;
- var cache = new WeakMap();
- _getRequireWildcardCache = function() {
- return cache;
- };
- return cache;
- }
- function _interopRequireWildcard(obj) {
- if (obj && obj.__esModule) {
- return obj;
- }
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
- return {default: obj};
- }
- var cache = _getRequireWildcardCache();
- if (cache && cache.has(obj)) {
- return cache.get(obj);
- }
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
- for (var key in obj) {
- if (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 defaultHead(inAmpMode = false) {
- const head = [/* @__PURE__ */ _react.default.createElement("meta", {charSet: "utf-8"})];
- if (!inAmpMode) {
- head.push(/* @__PURE__ */ _react.default.createElement("meta", {name: "viewport", content: "width=device-width"}));
- }
- return head;
- }
- function onlyReactElement(list, child) {
- if (typeof child === "string" || typeof child === "number") {
- return list;
- }
- if (child.type === _react.default.Fragment) {
- return list.concat(_react.default.Children.toArray(child.props.children).reduce((fragmentList, fragmentChild) => {
- if (typeof fragmentChild === "string" || typeof fragmentChild === "number") {
- return fragmentList;
- }
- return fragmentList.concat(fragmentChild);
- }, []));
- }
- return list.concat(child);
- }
- var METATYPES = ["name", "httpEquiv", "charSet", "itemProp"];
- function unique() {
- const keys = new Set();
- const tags = new Set();
- const metaTypes = new Set();
- const metaCategories = {};
- return (h) => {
- let isUnique = true;
- let hasKey = false;
- if (h.key && typeof h.key !== "number" && h.key.indexOf("$") > 0) {
- hasKey = true;
- const key = h.key.slice(h.key.indexOf("$") + 1);
- if (keys.has(key)) {
- isUnique = false;
- } else {
- keys.add(key);
- }
- }
- switch (h.type) {
- case "title":
- case "base":
- if (tags.has(h.type)) {
- isUnique = false;
- } else {
- tags.add(h.type);
- }
- break;
- case "meta":
- for (let i = 0, len = METATYPES.length; i < len; i++) {
- const metatype = METATYPES[i];
- if (!h.props.hasOwnProperty(metatype))
- continue;
- if (metatype === "charSet") {
- if (metaTypes.has(metatype)) {
- isUnique = false;
- } else {
- metaTypes.add(metatype);
- }
- } else {
- const category = h.props[metatype];
- const categories = metaCategories[metatype] || new Set();
- if ((metatype !== "name" || !hasKey) && categories.has(category)) {
- isUnique = false;
- } else {
- categories.add(category);
- metaCategories[metatype] = categories;
- }
- }
- }
- break;
- }
- return isUnique;
- };
- }
- function reduceComponents(headElements, props) {
- return headElements.reduce((list, headElement) => {
- const headElementChildren = _react.default.Children.toArray(headElement.props.children);
- return list.concat(headElementChildren);
- }, []).reduce(onlyReactElement, []).reverse().concat(defaultHead(props.inAmpMode)).filter(unique()).reverse().map((c, i) => {
- const key = c.key || i;
- if (false) {
- if (c.type === "link" && c.props["href"] && ["https://fonts.googleapis.com/css"].some((url) => c.props["href"].startsWith(url))) {
- const newProps = {...c.props || {}};
- newProps["data-href"] = newProps["href"];
- newProps["href"] = void 0;
- return /* @__PURE__ */ _react.default.cloneElement(c, newProps);
- }
- }
- return /* @__PURE__ */ _react.default.cloneElement(c, {key});
- });
- }
- function Head2({children}) {
- const ampState = (0, _react.useContext)(_ampContext.AmpStateContext);
- const headManager = (0, _react.useContext)(_headManagerContext.HeadManagerContext);
- return /* @__PURE__ */ _react.default.createElement(_sideEffect.default, {reduceComponentsToState: reduceComponents, headManager, inAmpMode: (0, _amp.isInAmpMode)(ampState)}, children);
- }
- Head2.rewind = () => {
- };
- var _default2 = Head2;
- exports.default = _default2;
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/head.js
- var require_head2 = __commonJS((exports, module) => {
- module.exports = require_head();
- });
-
- // src/api/demo/node_modules/.pnpm/@babel+runtime@7.12.5/node_modules/@babel/runtime/helpers/interopRequireDefault.js
- var require_interopRequireDefault = __commonJS((exports, module) => {
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- default: obj
- };
- }
- module.exports = _interopRequireDefault;
- });
-
- // src/api/demo/node_modules/.pnpm/@babel+runtime@7.12.5/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js
- var require_objectWithoutPropertiesLoose = __commonJS((exports, module) => {
- function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null)
- return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0)
- continue;
- target[key] = source[key];
- }
- return target;
- }
- module.exports = _objectWithoutPropertiesLoose;
- });
-
- // src/api/demo/node_modules/.pnpm/@babel+runtime@7.12.5/node_modules/@babel/runtime/helpers/extends.js
- var require_extends = __commonJS((exports, module) => {
- function _extends() {
- module.exports = _extends = Object.assign || function(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- module.exports = _extends;
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/next-server/lib/to-base-64.js
- var require_to_base_64 = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.toBase64 = toBase64;
- function toBase64(str) {
- if (typeof window === "undefined") {
- return Buffer.from(str).toString("base64");
- } else {
- return window.btoa(str);
- }
- }
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/next-server/server/image-config.js
- var require_image_config = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.imageConfigDefault = exports.VALID_LOADERS = void 0;
- var VALID_LOADERS = ["default", "imgix", "cloudinary", "akamai"];
- exports.VALID_LOADERS = VALID_LOADERS;
- var imageConfigDefault = {deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], path: "/_next/image", loader: "default", domains: []};
- exports.imageConfigDefault = imageConfigDefault;
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/client/request-idle-callback.js
- var require_request_idle_callback = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.cancelIdleCallback = exports.requestIdleCallback = void 0;
- var requestIdleCallback = typeof self !== "undefined" && self.requestIdleCallback || function(cb) {
- let start = Date.now();
- return setTimeout(function() {
- cb({didTimeout: false, timeRemaining: function() {
- return Math.max(0, 50 - (Date.now() - start));
- }});
- }, 1);
- };
- exports.requestIdleCallback = requestIdleCallback;
- var cancelIdleCallback = typeof self !== "undefined" && self.cancelIdleCallback || function(id) {
- return clearTimeout(id);
- };
- exports.cancelIdleCallback = cancelIdleCallback;
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/client/use-intersection.js
- var require_use_intersection = __commonJS((exports) => {
- "use strict";
- exports.__esModule = true;
- exports.useIntersection = useIntersection;
- var _react = require_react();
- var _requestIdleCallback = require_request_idle_callback();
- var hasIntersectionObserver = typeof IntersectionObserver !== "undefined";
- function useIntersection({rootMargin, disabled}) {
- const isDisabled = disabled || !hasIntersectionObserver;
- const unobserve = (0, _react.useRef)();
- const [visible, setVisible] = (0, _react.useState)(false);
- const setRef = (0, _react.useCallback)((el) => {
- if (unobserve.current) {
- unobserve.current();
- unobserve.current = void 0;
- }
- if (isDisabled || visible)
- return;
- if (el && el.tagName) {
- unobserve.current = observe(el, (isVisible) => isVisible && setVisible(isVisible), {rootMargin});
- }
- }, [isDisabled, rootMargin, visible]);
- (0, _react.useEffect)(() => {
- if (!hasIntersectionObserver) {
- if (!visible) {
- const idleCallback = (0, _requestIdleCallback.requestIdleCallback)(() => setVisible(true));
- return () => (0, _requestIdleCallback.cancelIdleCallback)(idleCallback);
- }
- }
- }, [visible]);
- return [setRef, visible];
- }
- function observe(element, callback, options) {
- const {id, observer, elements} = createObserver(options);
- elements.set(element, callback);
- observer.observe(element);
- return function unobserve() {
- elements.delete(element);
- observer.unobserve(element);
- if (elements.size === 0) {
- observer.disconnect();
- observers.delete(id);
- }
- };
- }
- var observers = new Map();
- function createObserver(options) {
- const id = options.rootMargin || "";
- let instance = observers.get(id);
- if (instance) {
- return instance;
- }
- const elements = new Map();
- const observer = new IntersectionObserver((entries) => {
- entries.forEach((entry) => {
- const callback = elements.get(entry.target);
- const isVisible = entry.isIntersecting || entry.intersectionRatio > 0;
- if (callback && isVisible) {
- callback(isVisible);
- }
- });
- }, options);
- observers.set(id, instance = {id, observer, elements});
- return instance;
- }
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/dist/client/image.js
- var require_image = __commonJS((exports) => {
- "use strict";
- var _interopRequireDefault = require_interopRequireDefault();
- exports.__esModule = true;
- exports.default = Image2;
- var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require_objectWithoutPropertiesLoose());
- var _extends2 = _interopRequireDefault(require_extends());
- var _react = _interopRequireDefault(require_react());
- var _head = _interopRequireDefault(require_head());
- var _toBase = require_to_base_64();
- var _imageConfig = require_image_config();
- var _useIntersection = require_use_intersection();
- if (typeof window === "undefined") {
- ;
- global.__NEXT_IMAGE_IMPORTED = true;
- }
- var VALID_LOADING_VALUES = ["lazy", "eager", void 0];
- var loaders = new Map([["imgix", imgixLoader], ["cloudinary", cloudinaryLoader], ["akamai", akamaiLoader], ["default", defaultLoader]]);
- var VALID_LAYOUT_VALUES = ["fill", "fixed", "intrinsic", "responsive", void 0];
- var {deviceSizes: configDeviceSizes, imageSizes: configImageSizes, loader: configLoader, path: configPath, domains: configDomains} = process.env.__NEXT_IMAGE_OPTS || _imageConfig.imageConfigDefault;
- var allSizes = [...configDeviceSizes, ...configImageSizes];
- configDeviceSizes.sort((a, b) => a - b);
- allSizes.sort((a, b) => a - b);
- function getWidths(width, layout, sizes) {
- if (sizes && (layout === "fill" || layout === "responsive")) {
- const percentSizes = [...sizes.matchAll(/(^|\s)(1?\d?\d)vw/g)].map((m) => parseInt(m[2]));
- if (percentSizes.length) {
- const smallestRatio = Math.min(...percentSizes) * 0.01;
- return {widths: allSizes.filter((s) => s >= configDeviceSizes[0] * smallestRatio), kind: "w"};
- }
- return {widths: allSizes, kind: "w"};
- }
- if (typeof width !== "number" || layout === "fill" || layout === "responsive") {
- return {widths: configDeviceSizes, kind: "w"};
- }
- const widths = [...new Set([width, width * 2].map((w) => allSizes.find((p) => p >= w) || allSizes[allSizes.length - 1]))];
- return {widths, kind: "x"};
- }
- function generateImgAttrs({src, unoptimized, layout, width, quality, sizes, loader}) {
- if (unoptimized) {
- return {src, srcSet: void 0, sizes: void 0};
- }
- const {widths, kind} = getWidths(width, layout, sizes);
- const last = widths.length - 1;
- return {
- sizes: !sizes && kind === "w" ? "100vw" : sizes,
- srcSet: widths.map((w, i) => `${loader({src, quality, width: w})} ${kind === "w" ? w : i + 1}${kind}`).join(", "),
- src: loader({src, quality, width: widths[last]})
- };
- }
- function getInt(x) {
- if (typeof x === "number") {
- return x;
- }
- if (typeof x === "string") {
- return parseInt(x, 10);
- }
- return void 0;
- }
- function defaultImageLoader(loaderProps) {
- const load = loaders.get(configLoader);
- if (load) {
- return load((0, _extends2.default)({root: configPath}, loaderProps));
- }
- throw new Error(`Unknown "loader" found in "next.config.js". Expected: ${_imageConfig.VALID_LOADERS.join(", ")}. Received: ${configLoader}`);
- }
- function Image2(_ref) {
- let {src, sizes, unoptimized = false, priority = false, loading, className, quality, width, height, objectFit, objectPosition, loader = defaultImageLoader} = _ref, all = (0, _objectWithoutPropertiesLoose2.default)(_ref, ["src", "sizes", "unoptimized", "priority", "loading", "className", "quality", "width", "height", "objectFit", "objectPosition", "loader"]);
- let rest = all;
- let layout = sizes ? "responsive" : "intrinsic";
- let unsized = false;
- if ("unsized" in rest) {
- unsized = Boolean(rest.unsized);
- delete rest["unsized"];
- } else if ("layout" in rest) {
- if (rest.layout)
- layout = rest.layout;
- delete rest["layout"];
- }
- if (true) {
- if (!src) {
- throw new Error(`Image is missing required "src" property. Make sure you pass "src" in props to the \`next/image\` component. Received: ${JSON.stringify({width, height, quality})}`);
- }
- if (!VALID_LAYOUT_VALUES.includes(layout)) {
- throw new Error(`Image with src "${src}" has invalid "layout" property. Provided "${layout}" should be one of ${VALID_LAYOUT_VALUES.map(String).join(",")}.`);
- }
- if (!VALID_LOADING_VALUES.includes(loading)) {
- throw new Error(`Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map(String).join(",")}.`);
- }
- if (priority && loading === "lazy") {
- throw new Error(`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`);
- }
- if (unsized) {
- throw new Error(`Image with src "${src}" has deprecated "unsized" property, which was removed in favor of the "layout='fill'" property`);
- }
- }
- let isLazy = !priority && (loading === "lazy" || typeof loading === "undefined");
- if (src && src.startsWith("data:")) {
- unoptimized = true;
- isLazy = false;
- }
- const [setRef, isIntersected] = (0, _useIntersection.useIntersection)({rootMargin: "200px", disabled: !isLazy});
- const isVisible = !isLazy || isIntersected;
- const widthInt = getInt(width);
- const heightInt = getInt(height);
- const qualityInt = getInt(quality);
- let wrapperStyle;
- let sizerStyle;
- let sizerSvg;
- let imgStyle = {position: "absolute", top: 0, left: 0, bottom: 0, right: 0, boxSizing: "border-box", padding: 0, border: "none", margin: "auto", display: "block", width: 0, height: 0, minWidth: "100%", maxWidth: "100%", minHeight: "100%", maxHeight: "100%", objectFit, objectPosition};
- if (typeof widthInt !== "undefined" && typeof heightInt !== "undefined" && layout !== "fill") {
- const quotient = heightInt / widthInt;
- const paddingTop = isNaN(quotient) ? "100%" : `${quotient * 100}%`;
- if (layout === "responsive") {
- wrapperStyle = {display: "block", overflow: "hidden", position: "relative", boxSizing: "border-box", margin: 0};
- sizerStyle = {display: "block", boxSizing: "border-box", paddingTop};
- } else if (layout === "intrinsic") {
- wrapperStyle = {display: "inline-block", maxWidth: "100%", overflow: "hidden", position: "relative", boxSizing: "border-box", margin: 0};
- sizerStyle = {boxSizing: "border-box", display: "block", maxWidth: "100%"};
- sizerSvg = `<svg width="${widthInt}" height="${heightInt}" xmlns="http://www.w3.org/2000/svg" version="1.1"/>`;
- } else if (layout === "fixed") {
- wrapperStyle = {overflow: "hidden", boxSizing: "border-box", display: "inline-block", position: "relative", width: widthInt, height: heightInt};
- }
- } else if (typeof widthInt === "undefined" && typeof heightInt === "undefined" && layout === "fill") {
- wrapperStyle = {display: "block", overflow: "hidden", position: "absolute", top: 0, left: 0, bottom: 0, right: 0, boxSizing: "border-box", margin: 0};
- } else {
- if (true) {
- throw new Error(`Image with src "${src}" must use "width" and "height" properties or "layout='fill'" property.`);
- }
- }
- let imgAttributes = {src: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", srcSet: void 0, sizes: void 0};
- if (isVisible) {
- imgAttributes = generateImgAttrs({src, unoptimized, layout, width: widthInt, quality: qualityInt, sizes, loader});
- }
- if (unsized) {
- wrapperStyle = void 0;
- sizerStyle = void 0;
- imgStyle = void 0;
- }
- return /* @__PURE__ */ _react.default.createElement("div", {style: wrapperStyle}, sizerStyle ? /* @__PURE__ */ _react.default.createElement("div", {style: sizerStyle}, sizerSvg ? /* @__PURE__ */ _react.default.createElement("img", {style: {maxWidth: "100%", display: "block", margin: 0, border: "none", padding: 0}, alt: "", "aria-hidden": true, role: "presentation", src: `data:image/svg+xml;base64,${(0, _toBase.toBase64)(sizerSvg)}`}) : null) : null, !isVisible && /* @__PURE__ */ _react.default.createElement("noscript", null, /* @__PURE__ */ _react.default.createElement("img", Object.assign({}, rest, generateImgAttrs({src, unoptimized, layout, width: widthInt, quality: qualityInt, sizes, loader}), {src, decoding: "async", sizes, style: imgStyle, className}))), /* @__PURE__ */ _react.default.createElement("img", Object.assign({}, rest, imgAttributes, {decoding: "async", className, ref: setRef, style: imgStyle})), priority ? /* @__PURE__ */ _react.default.createElement(_head.default, null, /* @__PURE__ */ _react.default.createElement("link", {
- key: "__nimg-" + imgAttributes.src + imgAttributes.srcSet + imgAttributes.sizes,
- rel: "preload",
- as: "image",
- href: imgAttributes.srcSet ? void 0 : imgAttributes.src,
- imagesrcset: imgAttributes.srcSet,
- imagesizes: imgAttributes.sizes
- })) : null);
- }
- function normalizeSrc(src) {
- return src[0] === "/" ? src.slice(1) : src;
- }
- function imgixLoader({root, src, width, quality}) {
- const params = ["auto=format", "fit=max", "w=" + width];
- let paramsString = "";
- if (quality) {
- params.push("q=" + quality);
- }
- if (params.length) {
- paramsString = "?" + params.join("&");
- }
- return `${root}${normalizeSrc(src)}${paramsString}`;
- }
- function akamaiLoader({root, src, width}) {
- return `${root}${normalizeSrc(src)}?imwidth=${width}`;
- }
- function cloudinaryLoader({root, src, width, quality}) {
- const params = ["f_auto", "c_limit", "w_" + width, "q_" + (quality || "auto")];
- let paramsString = params.join(",") + "/";
- return `${root}${paramsString}${normalizeSrc(src)}`;
- }
- function defaultLoader({root, src, width, quality}) {
- if (true) {
- const missingValues = [];
- if (!src)
- missingValues.push("src");
- if (!width)
- missingValues.push("width");
- if (missingValues.length > 0) {
- throw new Error(`Next Image Optimization requires ${missingValues.join(", ")} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify({src, width, quality})}`);
- }
- if (src.startsWith("//")) {
- throw new Error(`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`);
- }
- if (!src.startsWith("/") && configDomains) {
- let parsedSrc;
- try {
- parsedSrc = new URL(src);
- } catch (err) {
- console.error(err);
- throw new Error(`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`);
- }
- if (!configDomains.includes(parsedSrc.hostname)) {
- throw new Error(`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`
-See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`);
- }
- }
- }
- return `${root}?url=${encodeURIComponent(src)}&w=${width}&q=${quality || 75}`;
- }
- });
-
- // src/api/demo/node_modules/.pnpm/next@10.2.0_react-dom@17.0.2+react@17.0.2/node_modules/next/image.js
- var require_image2 = __commonJS((exports, module) => {
- module.exports = require_image();
- });
-
- // src/api/demo/pages/index.jsx
- var import_head = __toModule(require_head2());
- var import_image = __toModule(require_image2());
-
- // src/api/demo/styles/Home.module.css
- var _default = {};
-
- // src/api/demo/pages/index.jsx
- function Home() {
- return /* @__PURE__ */ React.createElement("div", {
- className: _default.container
- }, /* @__PURE__ */ React.createElement(import_head.default, null, /* @__PURE__ */ React.createElement("title", null, "Create Next App"), /* @__PURE__ */ React.createElement("meta", {
- name: "description",
- content: "Generated by create next app"
- }), /* @__PURE__ */ React.createElement("link", {
- rel: "icon",
- href: "/favicon.ico"
- })), /* @__PURE__ */ React.createElement("main", {
- className: _default.main
- }, /* @__PURE__ */ React.createElement("h1", {
- className: _default.title
- }, "Welcome to ", /* @__PURE__ */ React.createElement("a", {
- href: "https://nextjs.org"
- }, "Next.js!")), /* @__PURE__ */ React.createElement("p", {
- className: _default.description
- }, "Get started by editing", " ", /* @__PURE__ */ React.createElement("code", {
- className: _default.code
- }, "pages/index.js")), /* @__PURE__ */ React.createElement("div", {
- className: _default.grid
- }, /* @__PURE__ */ React.createElement("a", {
- href: "https://nextjs.org/docs",
- className: _default.card
- }, /* @__PURE__ */ React.createElement("h2", null, "Documentation \u2192"), /* @__PURE__ */ React.createElement("p", null, "Find in-depth information about Next.js features and API.")), /* @__PURE__ */ React.createElement("a", {
- href: "https://nextjs.org/learn",
- className: _default.card
- }, /* @__PURE__ */ React.createElement("h2", null, "Learn \u2192"), /* @__PURE__ */ React.createElement("p", null, "Learn about Next.js in an interactive course with quizzes!")), /* @__PURE__ */ React.createElement("a", {
- href: "https://github.com/vercel/next.js/tree/master/examples",
- className: _default.card
- }, /* @__PURE__ */ React.createElement("h2", null, "Examples \u2192"), /* @__PURE__ */ React.createElement("p", null, "Discover and deploy boilerplate example Next.js projects.")), /* @__PURE__ */ React.createElement("a", {
- href: "https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app",
- className: _default.card
- }, /* @__PURE__ */ React.createElement("h2", null, "Deploy \u2192"), /* @__PURE__ */ React.createElement("p", null, "Instantly deploy your Next.js site to a public URL with Vercel.")))), /* @__PURE__ */ React.createElement("footer", {
- className: _default.footer
- }, /* @__PURE__ */ React.createElement("a", {
- href: "https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app",
- target: "_blank",
- rel: "noopener noreferrer"
- }, "Powered by", " ", /* @__PURE__ */ React.createElement("span", {
- className: _default.logo
- }, /* @__PURE__ */ React.createElement(import_image.default, {
- src: "/vercel.svg",
- alt: "Vercel Logo",
- width: 72,
- height: 16
- })))));
- }
-})();
-/*
-object-assign
-(c) Sindre Sorhus
-@license MIT
-*/
-/** @license React v17.0.2
- * react.development.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
diff --git a/src/bundler.zig b/src/bundler.zig
index fe2592c00..c1ab43638 100644
--- a/src/bundler.zig
+++ b/src/bundler.zig
@@ -151,7 +151,7 @@ pub fn NewBundler(cache_files: bool) type {
linker: Linker,
timer: Timer = Timer{},
- pub const RuntimeCode = @embedFile("./runtime.js");
+ pub const isCacheEnabled = cache_files;
// to_bundle:
@@ -949,9 +949,30 @@ pub fn NewBundler(cache_files: bool) type {
js_printer.FileWriter,
js_printer.NewFileWriter(file),
);
+
+ var file_op = options.OutputFile.FileOperation.fromFile(file.handle, file_path.pretty);
+
+ file_op.fd = file.handle;
+
+ file_op.is_tmpdir = false;
+
+ if (Outstream == std.fs.Dir) {
+ file_op.dir = outstream.fd;
+
+ if (bundler.fs.fs.needToCloseFiles()) {
+ file.close();
+ file_op.fd = 0;
+ }
+ }
+
+ output_file.value = .{ .move = file_op };
},
.css => {
- const CSSWriter = Css.NewWriter(@TypeOf(file), @TypeOf(bundler.linker), import_path_format);
+ const CSSWriter = Css.NewWriter(
+ std.fs.File,
+ @TypeOf(&bundler.linker),
+ import_path_format,
+ );
const entry = bundler.resolver.caches.fs.readFile(
bundler.fs,
file_path.text,
@@ -963,27 +984,48 @@ pub fn NewBundler(cache_files: bool) type {
const _file = Fs.File{ .path = file_path, .contents = entry.contents };
const source = try logger.Source.initFile(_file, bundler.allocator);
- var css_writer = CSSWriter.init(&source, file, bundler.linker);
+ var css_writer = CSSWriter.init(
+ &source,
+ file,
+ &bundler.linker,
+ );
try css_writer.run(bundler.log, bundler.allocator);
output_file.size = css_writer.written;
- },
- // TODO:
- else => {},
- }
+ var file_op = options.OutputFile.FileOperation.fromFile(file.handle, file_path.pretty);
- var file_op = options.OutputFile.FileOperation.fromFile(file.handle, file_path.pretty);
+ file_op.fd = file.handle;
- file_op.fd = file.handle;
+ file_op.is_tmpdir = false;
- file_op.is_tmpdir = false;
- output_file.value = .{ .move = file_op };
- if (Outstream == std.fs.Dir) {
- file_op.dir = outstream.fd;
+ if (Outstream == std.fs.Dir) {
+ file_op.dir = outstream.fd;
- if (bundler.fs.fs.needToCloseFiles()) {
- file.close();
- file_op.fd = 0;
- }
+ if (bundler.fs.fs.needToCloseFiles()) {
+ file.close();
+ file_op.fd = 0;
+ }
+ }
+
+ output_file.value = .{ .move = file_op };
+ },
+ .file => {
+ var hashed_name = try bundler.linker.getHashedFilename(file_path, null);
+ var pathname = try bundler.allocator.alloc(u8, hashed_name.len + file_path.name.ext.len);
+ std.mem.copy(u8, pathname, hashed_name);
+ std.mem.copy(u8, pathname[hashed_name.len..], file_path.name.ext);
+ const dir = if (bundler.options.output_dir_handle) |output_handle| output_handle.fd else 0;
+
+ output_file.value = .{
+ .copy = options.OutputFile.FileOperation{
+ .pathname = pathname,
+ .dir = dir,
+ .is_outdir = true,
+ },
+ };
+ },
+
+ // // TODO:
+ // else => {},
}
return output_file;
diff --git a/src/cli.zig b/src/cli.zig
index 81f7b1c87..744369472 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -457,15 +457,7 @@ pub const Cli = struct {
// try f.moveTo(result.outbase, constStrToU8(rel_path), root_dir.fd);
},
.copy => |value| {
- const rel_path_base = resolve_path.relativeToCommonPath(
- from_path,
- from_path,
- f.input.text,
- filepath_buf[2..],
- comptime resolve_path.Platform.auto.separator(),
- false,
- );
- rel_path = filepath_buf[0 .. rel_path_base.len + 2];
+ rel_path = value.pathname;
try f.copyTo(result.outbase, constStrToU8(rel_path), root_dir.fd);
},
diff --git a/src/css_scanner.zig b/src/css_scanner.zig
index 11f0c69a2..42c7a5778 100644
--- a/src/css_scanner.zig
+++ b/src/css_scanner.zig
@@ -6,7 +6,9 @@ const import_record = @import("import_record.zig");
const logger = @import("./logger.zig");
const Options = options;
-const replacementCharacter = 0xFFFD;
+const _linker = @import("./linker.zig");
+
+const replacementCharacter: CodePoint = 0xFFFD;
pub const Chunk = struct {
// Entire chunk
@@ -20,7 +22,7 @@ pub const Chunk = struct {
};
pub fn raw(chunk: *const Chunk, source: *const logger.Source) string {
- return source.contents[chunk.range.loc.start..][0..chunk.range.len];
+ return source.contents[@intCast(usize, chunk.range.loc.start)..][0..@intCast(usize, chunk.range.len)];
}
// pub fn string(chunk: *const Chunk, source: *const logger.Source) string {
@@ -98,503 +100,626 @@ const escLineFeed = 0x0C;
// Once found, it resolves & rewrites them
// Eventually, there will be a real CSS parser in here.
// But, no time yet.
-pub fn NewScanner(
- comptime WriterType: type,
-) type {
- return struct {
- const Scanner = @This();
- current: usize = 0,
- start: usize = 0,
- end: usize = 0,
- log: *logger.Log,
+pub const Scanner = struct {
+ current: usize = 0,
+ start: usize = 0,
+ end: usize = 0,
+ log: *logger.Log,
+
+ has_newline_before: bool = false,
+ has_delimiter_before: bool = false,
+ allocator: *std.mem.Allocator,
+
+ source: *const logger.Source,
+ codepoint: CodePoint = -1,
+ approximate_newline_count: usize = 0,
+
+ pub fn init(log: *logger.Log, allocator: *std.mem.Allocator, source: *const logger.Source) Scanner {
+ return Scanner{ .log = log, .source = source, .allocator = allocator };
+ }
- has_newline_before: bool = false,
- has_delimiter_before: bool = false,
- allocator: *std.mem.Allocator,
+ pub fn range(scanner: *Scanner) logger.Range {
+ return logger.Range{
+ .loc = .{ .start = @intCast(i32, scanner.start) },
+ .len = @intCast(i32, scanner.end - scanner.start),
+ };
+ }
- source: *const logger.Source,
- writer: WriterType,
- codepoint: CodePoint = -1,
- approximate_newline_count: usize = 0,
+ pub fn step(scanner: *Scanner) void {
+ scanner.codepoint = scanner.nextCodepoint();
+ scanner.approximate_newline_count += @boolToInt(scanner.codepoint == '\n');
+ }
+ pub fn raw(scanner: *Scanner) string {}
+
+ pub fn isValidEscape(scanner: *Scanner) bool {
+ if (scanner.codepoint != '\\') return false;
+ const slice = scanner.nextCodepointSlice(false);
+ return switch (slice.len) {
+ 0 => false,
+ 1 => true,
+ 2 => (std.unicode.utf8Decode2(slice) catch 0) > 0,
+ 3 => (std.unicode.utf8Decode3(slice) catch 0) > 0,
+ 4 => (std.unicode.utf8Decode4(slice) catch 0) > 0,
+ else => false,
+ };
+ }
- pub fn init(log: *logger.Log, allocator: *std.mem.Allocator, writer: WriterType, source: *const logger.Source) Scanner {
- return Scanner{ .writer = writer, .log = log, .source = source, .allocator = allocator };
- }
+ pub fn consumeString(
+ scanner: *Scanner,
+ comptime quote: CodePoint,
+ ) ?string {
+ const start = scanner.current;
+ scanner.step();
- pub fn range(scanner: *Scanner) logger.Range {
- return logger.Range{
- .loc = .{ .start = @intCast(i32, scanner.start) },
- .len = @intCast(i32, scanner.end - scanner.start),
- };
+ while (true) {
+ switch (scanner.codepoint) {
+ '\\' => {
+ scanner.step();
+ // Handle Windows CRLF
+ if (scanner.codepoint == '\r') {
+ scanner.step();
+ if (scanner.codepoint == '\n') {
+ scanner.step();
+ }
+ continue;
+ }
+
+ // Otherwise, fall through to ignore the character after the backslash
+ },
+ -1 => {
+ scanner.end = scanner.current;
+ scanner.log.addRangeError(
+ scanner.source,
+ scanner.range(),
+ "Unterminated string token",
+ ) catch unreachable;
+ return null;
+ },
+ '\n', '\r', escLineFeed => {
+ scanner.end = scanner.current;
+ scanner.log.addRangeError(
+ scanner.source,
+ scanner.range(),
+ "Unterminated string token",
+ ) catch unreachable;
+ return null;
+ },
+ quote => {
+ const result = scanner.source.contents[start..scanner.end];
+ scanner.step();
+ return result;
+ },
+ else => {},
+ }
+ scanner.step();
}
+ unreachable;
+ }
- pub fn step(scanner: *Scanner) void {
- scanner.codepoint = scanner.nextCodepoint();
- scanner.approximate_newline_count += @boolToInt(scanner.codepoint == '\n');
+ pub fn consumeToEndOfMultiLineComment(scanner: *Scanner, start_range: logger.Range) void {
+ while (true) {
+ switch (scanner.codepoint) {
+ '*' => {
+ scanner.step();
+ if (scanner.codepoint == '/') {
+ scanner.step();
+ return;
+ }
+ },
+ -1 => {
+ scanner.log.addRangeError(scanner.source, start_range, "Expected \"*/\" to terminate multi-line comment") catch {};
+ return;
+ },
+ else => {
+ scanner.step();
+ },
+ }
}
- pub fn raw(scanner: *Scanner) string {}
-
- pub fn isValidEscape(scanner: *Scanner) bool {
- if (scanner.codepoint != '\\') return false;
- const slice = scanner.nextCodepointSlice(false);
- return switch (slice.len) {
- 0 => false,
- 1 => true,
- 2 => (std.unicode.utf8Decode2(slice) catch 0) > 0,
- 3 => (std.unicode.utf8Decode3(slice) catch 0) > 0,
- 4 => (std.unicode.utf8Decode4(slice) catch 0) > 0,
- else => false,
- };
+ }
+ pub fn consumeToEndOfSingleLineComment(scanner: *Scanner) void {
+ while (!isNewline(scanner.codepoint) and scanner.codepoint != -1) {
+ scanner.step();
}
- pub fn consumeString(scanner: *Scanner, comptime quote: CodePoint) ?string {
- const start = scanner.current;
- scanner.step();
+ scanner.log.addRangeWarning(
+ scanner.source,
+ scanner.range(),
+ "Comments in CSS use \"/* ... */\" instead of \"//\"",
+ ) catch {};
+ }
- while (true) {
- switch (scanner.codepoint) {
- '\\' => {
+ pub fn consumeURL(scanner: *Scanner) Chunk.TextContent {
+ var text = Chunk.TextContent{ .utf8 = "" };
+ const start = scanner.end;
+ validURL: while (true) {
+ switch (scanner.codepoint) {
+ ')' => {
+ text.utf8 = scanner.source.contents[start..scanner.end];
+ scanner.step();
+ return text;
+ },
+ -1 => {
+ const loc = logger.Loc{ .start = @intCast(i32, scanner.end) };
+ scanner.log.addError(scanner.source, loc, "Expected \")\" to end URL token") catch {};
+ return text;
+ },
+ '\t', '\n', '\r', escLineFeed => {
+ scanner.step();
+ while (isWhitespace(scanner.codepoint)) {
scanner.step();
- // Handle Windows CRLF
- if (scanner.codepoint == '\r') {
- scanner.step();
- if (scanner.codepoint == '\n') {
- scanner.step();
- }
- continue;
- }
+ }
- // Otherwise, fall through to ignore the character after the backslash
- },
- -1 => {
- scanner.end = scanner.current;
- scanner.log.addRangeError(
- scanner.source,
- scanner.range(),
- "Unterminated string token",
- ) catch unreachable;
- return null;
- },
- '\n', '\r', escLineFeed => {
- scanner.end = scanner.current;
- scanner.log.addRangeError(
- scanner.source,
- scanner.range(),
- "Unterminated string token",
- ) catch unreachable;
- return null;
- },
- quote => {
- scanner.step();
- return scanner.source.contents[start..scanner.current];
- },
- else => {},
- }
- scanner.step();
+ text.utf8 = scanner.source.contents[start..scanner.end];
+
+ if (scanner.codepoint != ')') {
+ const loc = logger.Loc{ .start = @intCast(i32, scanner.end) };
+ scanner.log.addError(scanner.source, loc, "Expected \")\" to end URL token") catch {};
+ break :validURL;
+ }
+ scanner.step();
+
+ return text;
+ },
+ '"', '\'', '(' => {
+ const r = logger.Range{ .loc = logger.Loc{ .start = @intCast(i32, start) }, .len = @intCast(i32, scanner.end - start) };
+
+ scanner.log.addRangeError(scanner.source, r, "Expected \")\" to end URL token") catch {};
+ break :validURL;
+ },
+ '\\' => {
+ text.needs_decode_escape = true;
+ if (!scanner.isValidEscape()) {
+ var loc = logger.Loc{
+ .start = @intCast(i32, scanner.end),
+ };
+ scanner.log.addError(scanner.source, loc, "Expected \")\" to end URL token") catch {};
+ break :validURL;
+ }
+ _ = scanner.consumeEscape();
+ },
+ else => {
+ if (isNonPrintable(scanner.codepoint)) {
+ const r = logger.Range{
+ .loc = logger.Loc{
+ .start = @intCast(i32, start),
+ },
+ .len = 1,
+ };
+ scanner.log.addRangeError(scanner.source, r, "Invalid escape") catch {};
+ break :validURL;
+ }
+ scanner.step();
+ },
+ }
+ }
+ text.valid = false;
+ // Consume the remnants of a bad url
+ while (true) {
+ switch (scanner.codepoint) {
+ ')', -1 => {
+ scanner.step();
+ text.utf8 = scanner.source.contents[start..scanner.end];
+ return text;
+ },
+ '\\' => {
+ text.needs_decode_escape = true;
+ if (scanner.isValidEscape()) {
+ _ = scanner.consumeEscape();
+ }
+ },
+ else => {},
}
- unreachable;
+
+ scanner.step();
}
- pub fn consumeURL(scanner: *Scanner) Chunk.TextContent {
- var text = Chunk.TextContent{ .utf8 = "" };
- const start = scanner.end;
- validURL: while (true) {
+ return text;
+ }
+
+ pub fn next(scanner: *Scanner, comptime WriterType: type, writer: WriterType, writeChunk: (fn (ctx: WriterType, Chunk) anyerror!void)) !void {
+ scanner.has_newline_before = scanner.end == 0;
+ scanner.has_delimiter_before = false;
+ scanner.step();
+
+ restart: while (true) {
+ var chunk = Chunk{
+ .range = logger.Range{
+ .loc = .{ .start = @intCast(i32, scanner.end) },
+ .len = 0,
+ },
+ .content = .{
+ .t_verbatim = .{},
+ },
+ };
+ scanner.start = scanner.end;
+
+ toplevel: while (true) {
+
+ // We only care about two things.
+ // 1. url()
+ // 2. @import
+ // To correctly parse, url(), we need to verify that the character preceding it is either whitespace, a colon, or a comma
+ // We also need to parse strings and comments, or else we risk resolving comments like this /* url(hi.jpg) */
switch (scanner.codepoint) {
- ')' => {
- scanner.step();
- text.utf8 = scanner.source.contents[start..scanner.current];
- return text;
- },
-1 => {
- const loc = logger.Loc{ .start = @intCast(i32, scanner.end) };
- scanner.log.addError(scanner.source, loc, "Expected \")\" to end URL token") catch {};
- return text;
+ chunk.range.len = @intCast(i32, scanner.end) - chunk.range.loc.start;
+ chunk.content.t_verbatim = .{};
+ try writeChunk(writer, chunk);
+ return;
},
- '\t', '\n', '\r', escLineFeed => {
- scanner.step();
- while (isWhitespace(scanner.codepoint)) {
- scanner.step();
- }
- if (scanner.codepoint != ')') {
- const loc = logger.Loc{ .start = @intCast(i32, scanner.end) };
- scanner.log.addError(scanner.source, loc, "Expected \")\" to end URL token") catch {};
- break :validURL;
- }
+ '\t', '\n', '\r', escLineFeed => {
+ scanner.has_newline_before = true;
scanner.step();
- text.utf8 = scanner.source.contents[start..scanner.current];
- return text;
+ continue;
},
- '"', '\'', '(' => {
- const r = logger.Range{ .loc = logger.Loc{ .start = @intCast(i32, start) }, .len = @intCast(i32, scanner.end - start) };
+ // Ensure whitespace doesn't affect scanner.has_delimiter_before
+ ' ' => {},
- scanner.log.addRangeError(scanner.source, r, "Expected \")\" to end URL token") catch {};
- break :validURL;
+ ':', ',' => {
+ scanner.has_delimiter_before = true;
},
- '\\' => {
- text.needs_decode_escape = true;
- if (!scanner.isValidEscape()) {
- var loc = logger.Loc{
- .start = @intCast(i32, scanner.end),
- };
- scanner.log.addError(scanner.source, loc, "Expected \")\" to end URL token") catch {};
- break :validURL;
- }
- _ = scanner.consumeEscape();
+ // this is a little hacky, but it should work since we're not parsing scopes
+ '{', '}', ';' => {
+ scanner.has_delimiter_before = false;
},
- else => {
- if (isNonPrintable(scanner.codepoint)) {
- const r = logger.Range{
- .loc = logger.Loc{
- .start = @intCast(i32, start),
- },
- .len = 1,
- };
- scanner.log.addRangeError(scanner.source, r, "Invalid escape") catch {};
- break :validURL;
+ 'u', 'U' => {
+ // url() always appears on the property value side
+ // so we should ignore it if it's part of a different token
+ if (!scanner.has_delimiter_before) {
+ scanner.step();
+ continue :toplevel;
}
+
+ var url_start = scanner.end;
scanner.step();
- },
- }
- }
- text.valid = false;
- // Consume the remnants of a bad url
- while (true) {
- switch (scanner.codepoint) {
- ')', -1 => {
+ switch (scanner.codepoint) {
+ 'r', 'R' => {},
+ else => {
+ continue;
+ },
+ }
scanner.step();
- text.utf8 = scanner.source.contents[start..scanner.end];
- return text;
- },
- '\\' => {
- text.needs_decode_escape = true;
- if (scanner.isValidEscape()) {
- _ = scanner.consumeEscape();
+ switch (scanner.codepoint) {
+ 'l', 'L' => {},
+ else => {
+ continue;
+ },
+ }
+ scanner.step();
+ if (scanner.codepoint != '(') {
+ continue;
}
- },
- else => {},
- }
- scanner.step();
- }
+ scanner.step();
- return text;
- }
+ var url_text: Chunk.TextContent = undefined;
- pub fn next(scanner: *Scanner) !void {
- scanner.has_newline_before = scanner.end == 0;
- scanner.has_delimiter_before = false;
- scanner.step();
+ switch (scanner.codepoint) {
+ '\'' => {
+ const str = scanner.consumeString('\'') orelse return error.SyntaxError;
+ if (scanner.codepoint != ')') {
+ continue;
+ }
+ scanner.step();
+ url_text = .{ .utf8 = str, .quote = .double };
+ },
+ '"' => {
+ const str = scanner.consumeString('"') orelse return error.SyntaxError;
+ if (scanner.codepoint != ')') {
+ continue;
+ }
+ scanner.step();
+ url_text = .{ .utf8 = str, .quote = .single };
+ },
+ else => {
+ url_text = scanner.consumeURL();
+ },
+ }
- restart: while (true) {
- var chunk = Chunk{
- .range = logger.Range{
- .loc = .{ .start = @intCast(i32, scanner.end) },
- .len = 0,
+ chunk.range.len = @intCast(i32, url_start) - chunk.range.loc.start;
+ chunk.content = .{ .t_verbatim = .{} };
+ // flush the pending chunk
+ try writeChunk(writer, chunk);
+ chunk.range.loc.start = @intCast(i32, url_start);
+ chunk.range.len = @intCast(i32, scanner.end) - chunk.range.loc.start;
+ chunk.content = .{ .t_url = url_text };
+ try writeChunk(writer, chunk);
+ scanner.has_delimiter_before = false;
+ continue :restart;
},
- .content = .{
- .t_verbatim = .{},
- },
- };
- scanner.start = scanner.end;
-
- toplevel: while (true) {
-
- // We only care about two things.
- // 1. url()
- // 2. @import
- // To correctly parse, url(), we need to verify that the character preceding it is either whitespace, a colon, or a comma
- // We also need to parse strings and comments, or else we risk resolving comments like this /* url(hi.jpg) */
- switch (scanner.codepoint) {
- -1 => {
- chunk.range.len = @intCast(i32, scanner.end) - chunk.range.loc.start;
- chunk.content.t_verbatim = .{};
- try scanner.writer.writeChunk(chunk);
- return;
- },
-
- '\t', '\n', '\r', escLineFeed => {
- scanner.has_newline_before = true;
- continue;
- },
- // Ensure whitespace doesn't affect scanner.has_delimiter_before
- ' ' => {},
-
- ':', ',' => {
- scanner.has_delimiter_before = true;
- },
- // this is a little hacky, but it should work since we're not parsing scopes
- '{', '}', ';' => {
- scanner.has_delimiter_before = false;
- },
- 'u', 'U' => {
- // url() always appears on the property value side
- // so we should ignore it if it's part of a different token
- if (!scanner.has_delimiter_before) {
- scanner.step();
- continue :toplevel;
- }
- var url_start = scanner.current;
- scanner.step();
- switch (scanner.codepoint) {
- 'r', 'R' => {},
- else => {
- continue;
- },
- }
- scanner.step();
- switch (scanner.codepoint) {
- 'l', 'L' => {},
- else => {
- continue;
- },
- }
- scanner.step();
- if (scanner.codepoint != '(') {
- continue;
- }
- const url_text = scanner.consumeURL();
- chunk.range.len = @intCast(i32, url_start) - chunk.range.loc.start;
- chunk.content = .{ .t_verbatim = .{} };
- // flush the pending chunk
- try scanner.writer.writeChunk(chunk);
- chunk.range.loc.start = @intCast(i32, url_start);
- chunk.range.len = @intCast(i32, scanner.end) - chunk.range.loc.start;
- chunk.content.t_url = url_text;
- try scanner.writer.writeChunk(chunk);
- scanner.has_delimiter_before = false;
- continue :restart;
- },
-
- '@' => {
- const start = scanner.end;
+ '@' => {
+ const start = scanner.end;
+ scanner.step();
+ if (scanner.codepoint != 'i') continue :toplevel;
+ scanner.step();
+ if (scanner.codepoint != 'm') continue :toplevel;
+ scanner.step();
+ if (scanner.codepoint != 'p') continue :toplevel;
+ scanner.step();
+ if (scanner.codepoint != 'o') continue :toplevel;
+ scanner.step();
+ if (scanner.codepoint != 'r') continue :toplevel;
+ scanner.step();
+ if (scanner.codepoint != 't') continue :toplevel;
+ scanner.step();
+ if (scanner.codepoint != ' ') continue :toplevel;
+
+ // Now that we know to expect an import url, we flush the chunk
+ chunk.range.len = @intCast(i32, start) - chunk.range.loc.start;
+ chunk.content = .{ .t_verbatim = .{} };
+ // flush the pending chunk
+ try writeChunk(writer, chunk);
+
+ // Don't write the .start until we know it's an @import rule
+ // We want to avoid messing with other rules
+ scanner.start = start;
+
+ var url_token_start = scanner.current;
+ var url_token_end = scanner.current;
+ // "Imported rules must precede all other types of rule"
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/@import
+ // @import url;
+ // @import url list-of-media-queries;
+ // @import url supports( supports-query );
+ // @import url supports( supports-query ) list-of-media-queries;
+
+ var is_url_token = false;
+ var quote: CodePoint = -1;
+ while (isWhitespace(scanner.codepoint)) {
scanner.step();
- if (scanner.codepoint != 'i') continue :toplevel;
- scanner.step();
- if (scanner.codepoint != 'm') continue :toplevel;
- scanner.step();
- if (scanner.codepoint != 'p') continue :toplevel;
- scanner.step();
- if (scanner.codepoint != 'o') continue :toplevel;
- scanner.step();
- if (scanner.codepoint != 'r') continue :toplevel;
- scanner.step();
- if (scanner.codepoint != 't') continue :toplevel;
- scanner.step();
- if (scanner.codepoint != 't') continue :toplevel;
- scanner.step();
- if (scanner.codepoint != ' ') continue :toplevel;
-
- // Now that we know to expect an import url, we flush the chunk
- chunk.range.len = @intCast(i32, start) - chunk.range.loc.start;
- chunk.content = .{ .t_verbatim = .{} };
- // flush the pending chunk
- try scanner.writer.writeChunk(chunk);
-
- // Don't write the .start until we know it's an @import rule
- // We want to avoid messing with other rules
- scanner.start = start;
-
- var url_token_start = scanner.current;
- var url_token_end = scanner.current;
- // "Imported rules must precede all other types of rule"
- // https://developer.mozilla.org/en-US/docs/Web/CSS/@import
- // @import url;
- // @import url list-of-media-queries;
- // @import url supports( supports-query );
- // @import url supports( supports-query ) list-of-media-queries;
-
- var is_url_token = false;
- var quote: CodePoint = -1;
- while (isWhitespace(scanner.codepoint)) {
- scanner.step();
- }
-
- var import = Chunk.Import{
- .text = .{
- .utf8 = "",
- },
- };
+ }
- switch (scanner.codepoint) {
- // spongebob-case url() are supported, I guess.
- // uRL()
- // uRL()
- // URl()
- 'u', 'U' => {
- scanner.step();
- switch (scanner.codepoint) {
- 'r', 'R' => {},
- else => {
- scanner.log.addError(
- scanner.source,
- logger.Loc{ .start = @intCast(i32, scanner.end) },
- "Expected @import to start with a string or url()",
- ) catch {};
- return error.SyntaxError;
- },
- }
- scanner.step();
- switch (scanner.codepoint) {
- 'l', 'L' => {},
- else => {
- scanner.log.addError(
- scanner.source,
- logger.Loc{ .start = @intCast(i32, scanner.end) },
- "Expected @import to start with a \", ' or url()",
- ) catch {};
- return error.SyntaxError;
- },
- }
- scanner.step();
- if (scanner.codepoint != '(') {
+ var import = Chunk.Import{
+ .text = .{
+ .utf8 = "",
+ },
+ };
+
+ switch (scanner.codepoint) {
+ // spongebob-case url() are supported, I guess.
+ // uRL()
+ // uRL()
+ // URl()
+ 'u', 'U' => {
+ scanner.step();
+ switch (scanner.codepoint) {
+ 'r', 'R' => {},
+ else => {
scanner.log.addError(
scanner.source,
logger.Loc{ .start = @intCast(i32, scanner.end) },
- "Expected \"(\" in @import url",
+ "Expected @import to start with a string or url()",
) catch {};
return error.SyntaxError;
- }
- import.text = scanner.consumeURL();
- },
- '"' => {
- import.text.quote = .double;
- if (scanner.consumeString('"')) |str| {
- import.text.utf8 = str;
- } else {
- return error.SyntaxError;
- }
- },
- '\'' => {
- import.text.quote = .single;
- if (scanner.consumeString('\'')) |str| {
- import.text.utf8 = str;
- } else {
+ },
+ }
+ scanner.step();
+ switch (scanner.codepoint) {
+ 'l', 'L' => {},
+ else => {
+ scanner.log.addError(
+ scanner.source,
+ logger.Loc{ .start = @intCast(i32, scanner.end) },
+ "Expected @import to start with a \", ' or url()",
+ ) catch {};
return error.SyntaxError;
- }
- },
- else => {
+ },
+ }
+ scanner.step();
+ if (scanner.codepoint != '(') {
+ scanner.log.addError(
+ scanner.source,
+ logger.Loc{ .start = @intCast(i32, scanner.end) },
+ "Expected \"(\" in @import url",
+ ) catch {};
return error.SyntaxError;
- },
- }
+ }
+
+ scanner.step();
- var suffix_start = scanner.end;
+ var url_text: Chunk.TextContent = undefined;
- get_suffix: while (true) {
switch (scanner.codepoint) {
- ';' => {
+ '\'' => {
+ const str = scanner.consumeString('\'') orelse return error.SyntaxError;
+ if (scanner.codepoint != ')') {
+ continue;
+ }
scanner.step();
- import.suffix = scanner.source.contents[suffix_start..scanner.end];
- scanner.has_delimiter_before = false;
- break :get_suffix;
+
+ url_text = .{ .utf8 = str, .quote = .single };
},
- -1 => {
- scanner.log.addError(
- scanner.source,
- logger.Loc{ .start = @intCast(i32, scanner.end) },
- "Expected \";\" at end of @import",
- ) catch {};
+ '"' => {
+ const str = scanner.consumeString('"') orelse return error.SyntaxError;
+ if (scanner.codepoint != ')') {
+ continue;
+ }
+ scanner.step();
+ url_text = .{ .utf8 = str, .quote = .double };
+ },
+ else => {
+ url_text = scanner.consumeURL();
},
- else => {},
}
- scanner.step();
- }
- chunk.range.len = @intCast(i32, scanner.end) - std.math.max(chunk.range.loc.start, 0);
- chunk.content = .{ .t_import = import };
- try scanner.writer.writeChunk(chunk);
- continue :restart;
- },
-
- // We don't actually care what the values are here, we just want to avoid confusing strings for URLs.
- '\'' => {
- scanner.has_delimiter_before = false;
- if (scanner.consumeString('\'') == null) {
- return error.SyntaxError;
- }
- },
- '"' => {
- scanner.has_delimiter_before = false;
- if (scanner.consumeString('"') == null) {
+
+ import.text = url_text;
+ },
+ '"' => {
+ import.text.quote = .double;
+ if (scanner.consumeString('"')) |str| {
+ import.text.utf8 = str;
+ } else {
+ return error.SyntaxError;
+ }
+ },
+ '\'' => {
+ import.text.quote = .single;
+ if (scanner.consumeString('\'')) |str| {
+ import.text.utf8 = str;
+ } else {
+ return error.SyntaxError;
+ }
+ },
+ else => {
return error.SyntaxError;
+ },
+ }
+
+ var suffix_start = scanner.end;
+
+ get_suffix: while (true) {
+ switch (scanner.codepoint) {
+ ';' => {
+ scanner.step();
+ import.suffix = scanner.source.contents[suffix_start..scanner.end];
+ scanner.has_delimiter_before = false;
+ break :get_suffix;
+ },
+ -1 => {
+ scanner.log.addError(
+ scanner.source,
+ logger.Loc{ .start = @intCast(i32, scanner.end) },
+ "Expected \";\" at end of @import",
+ ) catch {};
+ return;
+ },
+ else => {},
}
- },
- // Skip comments
- '/' => {},
- else => {
- scanner.has_delimiter_before = false;
- },
- }
+ scanner.step();
+ }
+ chunk.range.len = @intCast(i32, scanner.end) - std.math.max(chunk.range.loc.start, 0);
+ chunk.content = .{ .t_import = import };
+ try writeChunk(writer, chunk);
+ scanner.step();
+ continue :restart;
+ },
- scanner.step();
+ // We don't actually care what the values are here, we just want to avoid confusing strings for URLs.
+ '\'' => {
+ scanner.has_delimiter_before = false;
+ if (scanner.consumeString('\'') == null) {
+ return error.SyntaxError;
+ }
+ },
+ '"' => {
+ scanner.has_delimiter_before = false;
+ if (scanner.consumeString('"') == null) {
+ return error.SyntaxError;
+ }
+ },
+ // Skip comments
+ '/' => {
+ scanner.step();
+ switch (scanner.codepoint) {
+ '*' => {
+ scanner.step();
+ chunk.range.len = @intCast(i32, scanner.end);
+ scanner.consumeToEndOfMultiLineComment(chunk.range);
+ },
+ '/' => {
+ scanner.step();
+ scanner.consumeToEndOfSingleLineComment();
+ continue;
+ },
+ else => {
+ continue;
+ },
+ }
+ },
+ else => {
+ scanner.has_delimiter_before = false;
+ },
}
+
+ scanner.step();
}
}
+ }
+
+ pub fn consumeEscape(scanner: *Scanner) CodePoint {
+ scanner.step();
+
+ var c = scanner.codepoint;
- pub fn consumeEscape(scanner: *Scanner) CodePoint {
+ if (isHex(c)) |__hex| {
+ var hex = __hex;
scanner.step();
+ value: {
+ if (isHex(scanner.codepoint)) |_hex| {
+ scanner.step();
+ hex = hex * 16 + _hex;
+ } else {
+ break :value;
+ }
- var c = scanner.codepoint;
+ if (isHex(scanner.codepoint)) |_hex| {
+ scanner.step();
+ hex = hex * 16 + _hex;
+ } else {
+ break :value;
+ }
- if (isHex(c)) |__hex| {
- var hex = __hex;
- scanner.step();
- value: {
- comptime var i: usize = 0;
- inline while (i < 5) : (i += 1) {
- if (isHex(scanner.codepoint)) |_hex| {
- scanner.step();
- hex = hex * 16 + _hex;
- } else {
- break :value;
- }
- }
+ if (isHex(scanner.codepoint)) |_hex| {
+ scanner.step();
+ hex = hex * 16 + _hex;
+ } else {
break :value;
}
- if (isWhitespace(scanner.codepoint)) {
+ if (isHex(scanner.codepoint)) |_hex| {
scanner.step();
+ hex = hex * 16 + _hex;
+ } else {
+ break :value;
}
- return switch (hex) {
- 0, 0xD800...0xDFFF, 0x10FFFF...std.math.maxInt(CodePoint) => replacementCharacter,
- else => hex,
- };
- }
- if (c == -1) return replacementCharacter;
+ break :value;
+ }
- scanner.step();
- return c;
+ if (isWhitespace(scanner.codepoint)) {
+ scanner.step();
+ }
+ return switch (hex) {
+ 0, 0xD800...0xDFFF, 0x10FFFF...std.math.maxInt(CodePoint) => replacementCharacter,
+ else => hex,
+ };
}
- inline fn nextCodepointSlice(it: *Scanner, comptime advance: bool) []const u8 {
- @setRuntimeSafety(false);
+ if (c == -1) return replacementCharacter;
- const cp_len = strings.utf8ByteSequenceLength(it.source.contents[it.current]);
- if (advance) {
- it.end = it.current;
- it.current += cp_len;
- }
+ scanner.step();
+ return c;
+ }
- return if (!(it.current > it.source.contents.len)) it.source.contents[it.current - cp_len .. it.current] else "";
- }
+ inline fn nextCodepointSlice(it: *Scanner, comptime advance: bool) []const u8 {
+ @setRuntimeSafety(false);
- pub inline fn nextCodepoint(it: *Scanner) CodePoint {
- const slice = it.nextCodepointSlice(true);
- @setRuntimeSafety(false);
-
- return switch (slice.len) {
- 0 => -1,
- 1 => @intCast(CodePoint, slice[0]),
- 2 => @intCast(CodePoint, std.unicode.utf8Decode2(slice) catch unreachable),
- 3 => @intCast(CodePoint, std.unicode.utf8Decode3(slice) catch unreachable),
- 4 => @intCast(CodePoint, std.unicode.utf8Decode4(slice) catch unreachable),
- else => unreachable,
- };
+ const cp_len = strings.utf8ByteSequenceLength(it.source.contents[it.current]);
+ if (advance) {
+ it.end = it.current;
+ it.current += cp_len;
}
- };
-}
+
+ return if (!(it.current > it.source.contents.len)) it.source.contents[it.current - cp_len .. it.current] else "";
+ }
+
+ pub inline fn nextCodepoint(it: *Scanner) CodePoint {
+ const slice = it.nextCodepointSlice(true);
+ @setRuntimeSafety(false);
+
+ return switch (slice.len) {
+ 0 => -1,
+ 1 => @intCast(CodePoint, slice[0]),
+ 2 => @intCast(CodePoint, std.unicode.utf8Decode2(slice) catch unreachable),
+ 3 => @intCast(CodePoint, std.unicode.utf8Decode3(slice) catch unreachable),
+ 4 => @intCast(CodePoint, std.unicode.utf8Decode4(slice) catch unreachable),
+ else => unreachable,
+ };
+ }
+};
fn isWhitespace(c: CodePoint) bool {
return switch (c) {
@@ -603,6 +728,13 @@ fn isWhitespace(c: CodePoint) bool {
};
}
+fn isNewline(c: CodePoint) bool {
+ return switch (c) {
+ '\t', '\n', '\r', escLineFeed => true,
+ else => false,
+ };
+}
+
fn isNonPrintable(c: CodePoint) bool {
return switch (c) {
0...0x08, 0x0B, 0x0E...0x1F, 0x7F => true,
@@ -626,7 +758,6 @@ pub fn NewWriter(
) type {
return struct {
const Writer = @This();
- const Scanner = NewScanner(*Writer);
ctx: WriterType,
linker: LinkerType,
@@ -651,11 +782,10 @@ pub fn NewWriter(
log,
allocator,
- writer,
writer.source,
);
- try scanner.next();
+ try scanner.next(@TypeOf(writer), writer, writeChunk);
}
fn writeString(writer: *Writer, str: string, quote: Chunk.TextContent.Quote) !void {
diff --git a/src/darwin_c.zig b/src/darwin_c.zig
index 12f61d8ba..faeeea3c0 100644
--- a/src/darwin_c.zig
+++ b/src/darwin_c.zig
@@ -1,4 +1,4 @@
-pub usingnamespace @import("std").c.builtins;
+usingnamespace @import("std").c;
// int clonefileat(int src_dirfd, const char * src, int dst_dirfd, const char * dst, int flags);
pub extern "c" fn clonefileat(c_int, [*c]const u8, c_int, [*c]const u8, uint32_t: c_int) c_int;
@@ -11,5 +11,3 @@ pub extern "c" fn chmod([*c]const u8, mode_t) c_int;
pub extern "c" fn fchmod(c_int, mode_t) c_int;
pub extern "c" fn umask(mode_t) mode_t;
pub extern "c" fn fchmodat(c_int, [*c]const u8, mode_t, c_int) c_int;
-
-const mode_t = u16;
diff --git a/src/env.zig b/src/env.zig
new file mode 100644
index 000000000..2c680867c
--- /dev/null
+++ b/src/env.zig
@@ -0,0 +1,21 @@
+const std = @import("std");
+
+pub const BuildTarget = enum { native, wasm, wasi };
+pub const build_target: BuildTarget = {
+ if (std.Target.current.isWasm() and std.Target.current.getOsTag() == .wasi) {
+ return BuildTarget.wasi;
+ } else if (std.Target.current.isWasm()) {
+ return BuildTarget.wasm;
+ } else {
+ return BuildTarget.native;
+ }
+};
+
+pub const isWasm = build_target == .wasm;
+pub const isNative = build_target == .native;
+pub const isWasi = build_target == .wasi;
+pub const isMac = build_target == .native and std.Target.current.os.tag == .macos;
+pub const isBrowser = !isWasi and isWasm;
+pub const isWindows = std.Target.current.os.tag == .windows;
+pub const isDebug = std.builtin.Mode.Debug == std.builtin.mode;
+pub const isTest = std.builtin.is_test;
diff --git a/src/feature_flags.zig b/src/feature_flags.zig
new file mode 100644
index 000000000..0078d4cb9
--- /dev/null
+++ b/src/feature_flags.zig
@@ -0,0 +1,36 @@
+const env = @import("env.zig");
+
+pub const strong_etags_for_built_files = true;
+pub const keep_alive = true;
+
+// it just doesn't work well.
+pub const use_std_path_relative = false;
+pub const use_std_path_join = false;
+
+// Debug helpers
+pub const print_ast = false;
+pub const disable_printing_null = false;
+
+// This was a ~5% performance improvement
+pub const store_file_descriptors = !env.isWindows and !env.isBrowser;
+
+// This doesn't really seem to do anything for us
+pub const disable_filesystem_cache = false and std.Target.current.os.tag == .macos;
+
+pub const css_in_js_import_behavior = CSSModulePolyfill.facade;
+
+pub const only_output_esm = true;
+
+pub const jsx_runtime_is_cjs = true;
+
+pub const bundle_node_modules = true;
+
+pub const tracing = true;
+
+pub const verbose_watcher = true;
+
+pub const CSSModulePolyfill = enum {
+ // When you import a .css file and you reference the import in JavaScript
+ // Just return whatever the property key they referenced was
+ facade,
+};
diff --git a/src/fs.zig b/src/fs.zig
index 043a7bd19..dd5029b40 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -462,6 +462,34 @@ pub const FileSystem = struct {
mtime: i128 = 0,
mode: std.fs.File.Mode = 0,
+ threadlocal var hash_bytes: [32]u8 = undefined;
+ threadlocal var hash_name_buf: [1024]u8 = undefined;
+
+ pub fn hashName(
+ this: *const ModKey,
+ basename: string,
+ ) !string {
+
+ // We shouldn't just read the contents of the ModKey into memory
+ // The hash should be deterministic across computers and operating systems.
+ // inode is non-deterministic across volumes within the same compuiter
+ // so if we're not going to do a full content hash, we should use mtime and size.
+ // even mtime is debatable.
+ var hash_bytes_remain: []u8 = hash_bytes[0..];
+ std.mem.writeIntNative(@TypeOf(this.size), hash_bytes_remain[0..@sizeOf(@TypeOf(this.size))], this.size);
+ hash_bytes_remain = hash_bytes_remain[@sizeOf(@TypeOf(this.size))..];
+ std.mem.writeIntNative(@TypeOf(this.mtime), hash_bytes_remain[0..@sizeOf(@TypeOf(this.mtime))], this.mtime);
+
+ return try std.fmt.bufPrint(
+ &hash_name_buf,
+ "{s}-{x}",
+ .{
+ basename,
+ @truncate(u32, std.hash.Wyhash.hash(1, &hash_bytes)),
+ },
+ );
+ }
+
pub fn generate(fs: *RealFS, path: string, file: std.fs.File) anyerror!ModKey {
const stat = try file.stat();
diff --git a/src/global.zig b/src/global.zig
index 97727458f..3d985a930 100644
--- a/src/global.zig
+++ b/src/global.zig
@@ -2,63 +2,9 @@ const std = @import("std");
pub usingnamespace @import("strings.zig");
pub const C = @import("c.zig");
-pub const BuildTarget = enum { native, wasm, wasi };
-pub const build_target: BuildTarget = comptime {
- if (std.Target.current.isWasm() and std.Target.current.getOsTag() == .wasi) {
- return BuildTarget.wasi;
- } else if (std.Target.current.isWasm()) {
- return BuildTarget.wasm;
- } else {
- return BuildTarget.native;
- }
-};
-
-pub const isWasm = build_target == .wasm;
-pub const isNative = build_target == .native;
-pub const isWasi = build_target == .wasi;
-pub const isMac = build_target == .native and std.Target.current.os.tag == .macos;
-pub const isBrowser = !isWasi and isWasm;
-pub const isWindows = std.Target.current.os.tag == .windows;
-
-pub const FeatureFlags = struct {
- pub const strong_etags_for_built_files = true;
- pub const keep_alive = true;
-
- // it just doesn't work well.
- pub const use_std_path_relative = false;
- pub const use_std_path_join = false;
-
- // Debug helpers
- pub const print_ast = false;
- pub const disable_printing_null = false;
-
- // This was a ~5% performance improvement
- pub const store_file_descriptors = !isWindows and !isBrowser;
-
- // This doesn't really seem to do anything for us
- pub const disable_filesystem_cache = false and std.Target.current.os.tag == .macos;
-
- pub const css_in_js_import_behavior = CSSModulePolyfill.facade;
-
- pub const only_output_esm = true;
-
- pub const jsx_runtime_is_cjs = true;
-
- pub const bundle_node_modules = true;
-
- pub const tracing = true;
-
- pub const verbose_watcher = true;
-
- pub const CSSModulePolyfill = enum {
- // When you import a .css file and you reference the import in JavaScript
- // Just return whatever the property key they referenced was
- facade,
- };
-};
+pub usingnamespace @import("env.zig");
-pub const isDebug = std.builtin.Mode.Debug == std.builtin.mode;
-pub const isTest = std.builtin.is_test;
+pub const FeatureFlags = @import("feature_flags.zig");
pub const Output = struct {
threadlocal var source: *Source = undefined;
diff --git a/src/http.zig b/src/http.zig
index e818efd89..e6184915e 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -237,7 +237,7 @@ pub const RequestContext = struct {
ctx.appendHeader("Transfer-Encoding", "Chunked");
} else {
const length_str = try ctx.allocator.alloc(u8, 64);
- ctx.appendHeader("Content-Length", length_str[0..std.fmt.formatIntBuf(length_str, length, 10, true, .{})]);
+ ctx.appendHeader("Content-Length", length_str[0..std.fmt.formatIntBuf(length_str, length, 10, .upper, .{})]);
}
try ctx.flushHeaders();
@@ -952,7 +952,7 @@ pub const RequestContext = struct {
if (FeatureFlags.strong_etags_for_built_files) {
if (buf.len < 16 * 16 * 16 * 16) {
const strong_etag = std.hash.Wyhash.hash(1, buf);
- const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, true, .{});
+ const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
chunky.rctx.appendHeader("ETag", etag_content_slice);
@@ -1047,7 +1047,7 @@ pub const RequestContext = struct {
weak_etag.update(weak_etag_tmp_buffer[0..16]);
}
- const etag_content_slice = std.fmt.bufPrintIntToSlice(weak_etag_buffer[2..], weak_etag.final(), 16, true, .{});
+ const etag_content_slice = std.fmt.bufPrintIntToSlice(weak_etag_buffer[2..], weak_etag.final(), 16, .upper, .{});
const complete_weak_etag = weak_etag_buffer[0 .. etag_content_slice.len + 2];
ctx.appendHeader("ETag", complete_weak_etag);
@@ -1101,7 +1101,7 @@ pub const RequestContext = struct {
if (FeatureFlags.strong_etags_for_built_files) {
// TODO: don't hash runtime.js
const strong_etag = std.hash.Wyhash.hash(1, buffer);
- const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, true, .{});
+ const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
ctx.appendHeader("ETag", etag_content_slice);
diff --git a/src/js_printer.zig b/src/js_printer.zig
index a15b9f3c7..d55473481 100644
--- a/src/js_printer.zig
+++ b/src/js_printer.zig
@@ -482,7 +482,7 @@ pub fn NewPrinter(
// In JavaScript, numbers are represented as 64 bit floats
// However, they could also be signed or unsigned int 32 (when doing bit shifts)
// In this case, it's always going to unsigned since that conversion has already happened.
- std.fmt.formatInt(@floatToInt(u32, float), 10, true, .{}, p) catch unreachable;
+ std.fmt.formatInt(@floatToInt(u32, float), 10, .upper, .{}, p) catch unreachable;
return;
}
@@ -3274,7 +3274,7 @@ pub fn NewPrinter(
pub fn printLoadFromBundleWithoutCall(p: *Printer, import_record_index: u32) void {
const record = p.import_records[import_record_index];
p.print("$");
- std.fmt.formatInt(record.module_id, 16, false, .{}, p) catch unreachable;
+ std.fmt.formatInt(record.module_id, 16, .lower, .{}, p) catch unreachable;
}
pub fn printBundledRequire(p: *Printer, require: E.Require) void {
if (p.import_records[require.import_record_index].is_internal) {
@@ -3426,7 +3426,7 @@ pub fn NewPrinter(
p.print("// ");
p.print(p.options.source_path.?.pretty);
p.print("\nexport var $");
- std.fmt.formatInt(p.options.module_hash, 16, false, .{}, p) catch unreachable;
+ std.fmt.formatInt(p.options.module_hash, 16, .lower, .{}, p) catch unreachable;
p.print(" = ");
p.printExpr(decls[0].value.?, .comma, ExprFlag.None());
p.printSemicolonAfterStatement();
diff --git a/src/linker.zig b/src/linker.zig
index 550b48590..9c20718e0 100644
--- a/src/linker.zig
+++ b/src/linker.zig
@@ -28,8 +28,11 @@ const Bundler = _bundler.Bundler;
const ResolveQueue = _bundler.ResolveQueue;
const Runtime = @import("./runtime.zig").Runtime;
+pub const CSSResolveError = error{ResolveError};
+
pub fn NewLinker(comptime BundlerType: type) type {
return struct {
+ const HashedFileNameMap = std.AutoHashMap(u64, string);
const ThisLinker = @This();
allocator: *std.mem.Allocator,
options: *Options.BundleOptions,
@@ -41,6 +44,7 @@ pub fn NewLinker(comptime BundlerType: type) type {
any_needs_runtime: bool = false,
runtime_import_record: ?ImportRecord = null,
runtime_source_path: string,
+ hashed_filenames: HashedFileNameMap,
pub fn init(
allocator: *std.mem.Allocator,
@@ -62,6 +66,7 @@ pub fn NewLinker(comptime BundlerType: type) type {
.resolver = resolver,
.resolve_results = resolve_results,
.runtime_source_path = fs.absAlloc(allocator, &([_]string{"__runtime.js"})) catch unreachable,
+ .hashed_filenames = HashedFileNameMap.init(allocator),
};
}
@@ -71,35 +76,87 @@ pub fn NewLinker(comptime BundlerType: type) type {
return RequireOrImportMeta{};
}
- pub fn resolveCSS(
+ pub fn getHashedFilename(
this: *ThisLinker,
+ file_path: Fs.Path,
+ fd: ?FileDescriptorType,
+ ) !string {
+ if (BundlerType.isCacheEnabled) {
+ var hashed = std.hash.Wyhash.hash(0, file_path.text);
+ var hashed_result = try this.hashed_filenames.getOrPut(hashed);
+ if (hashed_result.found_existing) {
+ return hashed_result.value_ptr.*;
+ }
+ }
+
+ var file: std.fs.File = if (fd) |_fd| std.fs.File{ .handle = _fd } else try std.fs.openFileAbsolute(file_path.text, .{ .read = true });
+ Fs.FileSystem.setMaxFd(file.handle);
+ var modkey = try Fs.FileSystem.RealFS.ModKey.generate(&this.fs.fs, file_path.text, file);
+ const hash_name = try modkey.hashName(file_path.name.base);
+
+ if (BundlerType.isCacheEnabled) {
+ var hashed = std.hash.Wyhash.hash(0, file_path.text);
+ try this.hashed_filenames.put(hashed, try this.allocator.dupe(u8, hash_name));
+ }
+
+ if (this.fs.fs.needToCloseFiles() and fd == null) {
+ file.close();
+ }
+
+ return hash_name;
+ }
+
+ pub fn resolveCSS(
+ this: anytype,
path: Fs.Path,
url: string,
range: logger.Range,
- comptime kind: ImportKind,
+ kind: ImportKind,
comptime import_path_format: Options.BundleOptions.ImportPathFormat,
) !string {
+ const dir = path.name.dirWithTrailingSlash();
+
switch (kind) {
.at => {
- var resolve_result = try this.resolver.resolve(path.name.dir, url, .at);
+ var resolve_result = try this.resolver.resolve(dir, url, .at);
+ if (resolve_result.is_external) {
+ return resolve_result.path_pair.primary.text;
+ }
+
var import_record = ImportRecord{ .range = range, .path = resolve_result.path_pair.primary, .kind = kind };
- try this.processImportRecord(path.name.dir, &resolve_result, &import_record, import_path_format);
+
+ const loader = this.options.loaders.get(resolve_result.path_pair.primary.name.ext) orelse .file;
+
+ this.processImportRecord(loader, dir, &resolve_result, &import_record, import_path_format) catch unreachable;
return import_record.path.text;
},
.at_conditional => {
- var resolve_result = try this.resolver.resolve(path.name.dir, url, .at_conditional);
+ var resolve_result = try this.resolver.resolve(dir, url, .at_conditional);
+ if (resolve_result.is_external) {
+ return resolve_result.path_pair.primary.text;
+ }
+
var import_record = ImportRecord{ .range = range, .path = resolve_result.path_pair.primary, .kind = kind };
- try this.processImportRecord(path.name.dir, &resolve_result, &import_record, import_path_format);
+ const loader = this.options.loaders.get(resolve_result.path_pair.primary.name.ext) orelse .file;
+
+ this.processImportRecord(loader, dir, &resolve_result, &import_record, import_path_format) catch unreachable;
return import_record.path.text;
},
.url => {
- var resolve_result = try this.resolver.resolve(path.name.dir, url, .url);
+ var resolve_result = try this.resolver.resolve(dir, url, .url);
+ if (resolve_result.is_external) {
+ return resolve_result.path_pair.primary.text;
+ }
+
var import_record = ImportRecord{ .range = range, .path = resolve_result.path_pair.primary, .kind = kind };
- try this.processImportRecord(path.name.dir, &resolve_result, &import_record, import_path_format);
+ const loader = this.options.loaders.get(resolve_result.path_pair.primary.name.ext) orelse .file;
+
+ this.processImportRecord(loader, dir, &resolve_result, &import_record, import_path_format) catch unreachable;
return import_record.path.text;
},
else => unreachable,
}
+ unreachable;
}
// pub const Scratch = struct {
@@ -137,6 +194,7 @@ pub fn NewLinker(comptime BundlerType: type) type {
source_dir,
linker.runtime_source_path,
Runtime.version(),
+ false,
import_path_format,
);
result.ast.runtime_import_record_id = record_index;
@@ -214,6 +272,8 @@ pub fn NewLinker(comptime BundlerType: type) type {
}
linker.processImportRecord(
+ linker.options.loaders.get(resolved_import.path_pair.primary.name.ext) orelse .file,
+
// Include trailing slash
file_path.text[0 .. source_dir.len + 1],
resolved_import,
@@ -290,6 +350,7 @@ pub fn NewLinker(comptime BundlerType: type) type {
source_dir,
linker.runtime_source_path,
Runtime.version(),
+ false,
import_path_format,
),
.range = logger.Range{ .loc = logger.Loc{ .start = 0 }, .len = 0 },
@@ -355,18 +416,54 @@ pub fn NewLinker(comptime BundlerType: type) type {
source_dir: string,
source_path: string,
package_version: ?string,
+ use_hashed_name: bool,
comptime import_path_format: Options.BundleOptions.ImportPathFormat,
) !Fs.Path {
switch (import_path_format) {
.relative => {
- var pretty = try linker.allocator.dupe(u8, linker.fs.relative(source_dir, source_path));
- var pathname = Fs.PathName.init(pretty);
- return Fs.Path.initWithPretty(pretty, pretty);
+ var relative_name = linker.fs.relative(source_dir, source_path);
+ var pretty: string = undefined;
+ if (use_hashed_name) {
+ var basepath = Fs.Path.init(source_path);
+ const basename = try linker.getHashedFilename(basepath, null);
+ var dir = basepath.name.dirWithTrailingSlash();
+ var _pretty = try linker.allocator.alloc(u8, dir.len + basename.len + basepath.name.ext.len);
+ std.mem.copy(u8, _pretty, dir);
+ var remaining_pretty = _pretty[dir.len..];
+ std.mem.copy(u8, remaining_pretty, basename);
+ remaining_pretty = remaining_pretty[basename.len..];
+ std.mem.copy(u8, remaining_pretty, basepath.name.ext);
+ pretty = _pretty;
+ relative_name = try linker.allocator.dupe(u8, relative_name);
+ } else {
+ pretty = try linker.allocator.dupe(u8, relative_name);
+ relative_name = pretty;
+ }
+
+ return Fs.Path.initWithPretty(pretty, relative_name);
},
.relative_nodejs => {
- var pretty = try linker.allocator.dupe(u8, linker.fs.relative(source_dir, source_path));
+ var relative_name = linker.fs.relative(source_dir, source_path);
+ var pretty: string = undefined;
+ if (use_hashed_name) {
+ var basepath = Fs.Path.init(source_path);
+ const basename = try linker.getHashedFilename(basepath, null);
+ var dir = basepath.name.dirWithTrailingSlash();
+ var _pretty = try linker.allocator.alloc(u8, dir.len + basename.len + basepath.name.ext.len);
+ std.mem.copy(u8, _pretty, dir);
+ var remaining_pretty = _pretty[dir.len..];
+ std.mem.copy(u8, remaining_pretty, basename);
+ remaining_pretty = remaining_pretty[basename.len..];
+ std.mem.copy(u8, remaining_pretty, basepath.name.ext);
+ pretty = _pretty;
+ relative_name = try linker.allocator.dupe(u8, relative_name);
+ } else {
+ pretty = try linker.allocator.dupe(u8, relative_name);
+ relative_name = pretty;
+ }
+
var pathname = Fs.PathName.init(pretty);
- var path = Fs.Path.initWithPretty(pretty, pretty);
+ var path = Fs.Path.initWithPretty(pretty, relative_name);
path.text = path.text[0 .. path.text.len - path.name.ext.len];
return path;
},
@@ -385,33 +482,27 @@ pub fn NewLinker(comptime BundlerType: type) type {
base = base[0..dot];
}
- if (linker.options.append_package_version_in_query_string and package_version != null) {
- const absolute_url =
- try std.fmt.allocPrint(
- linker.allocator,
- "{s}{s}{s}?v={s}",
- .{
- linker.options.public_url,
- base,
- absolute_pathname.ext,
- package_version.?,
- },
- );
-
- return Fs.Path.initWithPretty(absolute_url, absolute_url);
- } else {
- const absolute_url = try std.fmt.allocPrint(
- linker.allocator,
- "{s}{s}{s}",
- .{
- linker.options.public_url,
- base,
- absolute_pathname.ext,
- },
- );
-
- return Fs.Path.initWithPretty(absolute_url, absolute_url);
+ var dirname = std.fs.path.dirname(base) orelse "";
+
+ var basename = std.fs.path.basename(base);
+
+ if (use_hashed_name) {
+ var basepath = Fs.Path.init(source_path);
+ basename = try linker.getHashedFilename(basepath, null);
}
+
+ const absolute_url = try std.fmt.allocPrint(
+ linker.allocator,
+ "{s}{s}{s}{s}",
+ .{
+ linker.options.public_url,
+ dirname,
+ basename,
+ absolute_pathname.ext,
+ },
+ );
+
+ return Fs.Path.initWithPretty(absolute_url, absolute_url);
},
else => unreachable,
@@ -420,6 +511,7 @@ pub fn NewLinker(comptime BundlerType: type) type {
pub fn processImportRecord(
linker: *ThisLinker,
+ loader: Options.Loader,
source_dir: string,
resolve_result: *Resolver.Result,
import_record: *ImportRecord,
@@ -440,6 +532,7 @@ pub fn NewLinker(comptime BundlerType: type) type {
source_dir,
resolve_result.path_pair.primary.text,
if (resolve_result.package_json) |package_json| package_json.version else "",
+ BundlerType.isCacheEnabled and loader == .file,
import_path_format,
);
}
diff --git a/src/options.zig b/src/options.zig
index 204f457e1..e9f48ee17 100644
--- a/src/options.zig
+++ b/src/options.zig
@@ -607,7 +607,7 @@ pub const BundleOptions = struct {
};
pub const Defaults = struct {
- pub var ExtensionOrder = [_]string{ ".tsx", ".ts", ".jsx", ".js", ".json" };
+ pub var ExtensionOrder = [_]string{ ".tsx", ".ts", ".jsx", ".js", ".json", ".css" };
};
pub fn fromApi(
@@ -860,6 +860,7 @@ pub const OutputFile = struct {
fd: FileDescriptorType = 0,
dir: FileDescriptorType = 0,
is_tmpdir: bool = false,
+ is_outdir: bool = false,
pub fn fromFile(fd: FileDescriptorType, pathname: string) FileOperation {
return .{
@@ -939,16 +940,6 @@ pub const OutputFile = struct {
pub fn copyTo(file: *const OutputFile, base_path: string, rel_path: []u8, dir: FileDescriptorType) !void {
var copy = file.value.copy;
- if (isMac and copy.fd > 0) {
- // First try using a copy-on-write clonefile()
- // this will fail if the destination already exists
- rel_path.ptr[rel_path.len + 1] = 0;
- var rel_c_path = rel_path.ptr[0..rel_path.len :0];
- const success = C.fclonefileat(copy.fd, dir, rel_c_path, 0) == 0;
- if (success) {
- return;
- }
- }
var dir_obj = std.fs.Dir{ .fd = dir };
const file_out = (try dir_obj.createFile(rel_path, .{}));
@@ -956,7 +947,7 @@ pub const OutputFile = struct {
const fd_out = file_out.handle;
var do_close = false;
// TODO: close file_out on error
- const fd_in = if (copy.fd > 0) copy.fd else (try std.fs.openFileAbsolute(copy.getPathname(), .{ .read = true })).handle;
+ const fd_in = (try std.fs.openFileAbsolute(file.input.text, .{ .read = true })).handle;
if (isNative) {
Fs.FileSystem.setMaxFd(fd_out);
diff --git a/src/resolver/resolve_path.zig b/src/resolver/resolve_path.zig
index 2bbd83c55..1bba7d12c 100644
--- a/src/resolver/resolve_path.zig
+++ b/src/resolver/resolve_path.zig
@@ -1,6 +1,6 @@
const tester = @import("../test/tester.zig");
-const FeatureFlags = @import("../global.zig").FeatureFlags;
+const FeatureFlags = @import("../feature_flags.zig");
const std = @import("std");
threadlocal var parser_join_input_buffer: [1024]u8 = undefined;
@@ -259,7 +259,7 @@ pub fn relativeToCommonPath(
var out_slice: []u8 = buf[0..0];
if (normalized_from.len > 0) {
- var i: usize = @boolToInt(normalized_from[0] == separator) + 1 + last_common_separator;
+ var i: usize = @intCast(usize, @boolToInt(normalized_from[0] == separator)) + 1 + last_common_separator;
while (i <= normalized_from.len) : (i += 1) {
if (i == normalized_from.len or (normalized_from[i] == separator and i + 1 < normalized_from.len)) {
diff --git a/src/test/fixtures/me@2x.jpeg b/src/test/fixtures/me@2x.jpeg
new file mode 100644
index 000000000..02f8a3b19
--- /dev/null
+++ b/src/test/fixtures/me@2x.jpeg
Binary files differ
diff --git a/src/test/fixtures/simple.css b/src/test/fixtures/simple.css
new file mode 100644
index 000000000..63b3aa46e
--- /dev/null
+++ b/src/test/fixtures/simple.css
@@ -0,0 +1,1205 @@
+@import url("./test-import.css");
+
+* {
+ box-sizing: border-box;
+
+ background-image: url("./me@2x.jpeg");
+}
+
+:root {
+ --heading-font: "Space Mono", system-ui;
+ --body-font: "IBM Plex Sans", system-ui;
+
+ --color-brand: #02ff00;
+ --color-brand-muted: rgb(2, 150, 0);
+
+ --padding-horizontal: 90px;
+
+ --page-background: black;
+ --page-background-alpha: rgba(0, 0, 0, 0.8);
+
+ --result__background-color: black;
+ --result__primary-color: var(--color-brand);
+ --result__foreground-color: white;
+ --result__muted-color: rgb(165, 165, 165);
+
+ --card-width: 352px;
+
+ --page-width: 1152px;
+
+ --snippets_container-background-unfocused: #171717;
+ --snippets_container-background-focused: #0017e9;
+ --snippets_container-background: var(
+ --snippets_container-background-unfocused
+ );
+ --snippets_container-muted-color: rgb(153, 153, 153);
+}
+
+html,
+body {
+ padding: 0;
+ margin: 0;
+}
+
+body {
+ font-family: var(--body-font);
+ background-color: var(--page-background);
+ color: white;
+}
+
+a {
+ color: inherit;
+ text-decoration: none;
+}
+
+* {
+ box-sizing: border-box;
+ font-variant-ligatures: no-common-ligatures;
+}
+
+h1,
+h2,
+h3 {
+ font-family: var(--heading-font);
+ font-weight: normal;
+}
+
+.NavigationContainer {
+ display: grid;
+ grid-template-columns: min-content min-content min-content;
+ align-items: center;
+}
+
+.NavigationLink,
+.NavigationLink:visited {
+ font-weight: 500;
+ font-family: var(--heading-font);
+ font-size: 0.9rem;
+ letter-spacing: 0.05rem;
+ text-transform: uppercase;
+ display: block;
+ text-decoration: none;
+}
+
+.SnippetList {
+ scroll-margin-top: 200px;
+}
+
+.SnippetList,
+.NewBenchmarkPageContent {
+ display: grid;
+ grid-row-gap: 16px;
+}
+
+.NewBenchmarkPageContent {
+ margin-top: 24px;
+ margin-bottom: 42px;
+}
+
+.NavigationLink:hover {
+ border-bottom-color: var(--color-brand);
+}
+
+.NavigationLink--inactive {
+ color: rgb(165, 165, 165);
+}
+
+.NavigationLink--active {
+ color: var(--color-brand);
+}
+
+.NavigationLink--inactive:hover {
+ cursor: pointer;
+ color: var(--color-brand);
+}
+
+.LandingHeader-Container {
+ padding: 0 var(--padding-horizontal);
+ backdrop-filter: blur(5px);
+ background-color: var(--page-background-alpha);
+ position: sticky;
+ top: 0;
+ z-index: 999;
+ padding-bottom: 1.2em;
+ mask-image: linear-gradient(to bottom, black 85%, transparent);
+}
+
+.LandingHeader {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 34px var(--padding-horizontal);
+}
+
+.HeroContainer {
+ padding: 34px var(--padding-horizontal);
+ width: 100%;
+ display: flex;
+}
+
+.Gallery,
+.HeroContainer,
+.LandingHeader {
+ max-width: var(--page-width);
+ margin: 0 auto;
+}
+
+.GalleryList {
+ padding: 34px var(--padding-horizontal);
+}
+
+.GalleryList {
+ display: grid;
+ grid-gap: 16px;
+ grid-template-columns: repeat(auto-fit, var(--card-width));
+}
+
+.HeroContainer {
+ align-items: center;
+}
+
+.Hero {
+ flex: 1;
+}
+
+.Description {
+ margin-bottom: 24px;
+}
+
+.Tagline,
+.Hero-demo {
+ margin-block-start: 0.67em;
+ margin-block-end: 0.67em;
+}
+
+.Hero-demo {
+ margin-left: 48px;
+}
+
+.Tagline {
+ font-size: 2.2rem;
+}
+
+.RunTestButtonContainer {
+ position: sticky;
+}
+
+.LinkButton {
+ color: black;
+ background: none;
+ outline: none;
+ background-color: var(--color-brand);
+ font-weight: bold;
+ font-family: var(--heading-font);
+ font-size: 1.2rem;
+ padding: 10px 17px;
+ text-transform: uppercase;
+ width: min-content;
+ text-decoration: none;
+
+ white-space: nowrap;
+ cursor: pointer;
+ display: flex;
+ justify-content: space-between;
+ transition: transform 0.1s linear;
+}
+
+.LinkButton:hover {
+ transform: scale(1.03, 1.03);
+}
+
+.LinkButton-arrow {
+ animation: arrow-move-animation 1s ease-in-out;
+ animation-iteration-count: infinite;
+ animation-direction: alternate;
+ animation-delay: 0.1s;
+ transform: translateX(0px) scale(1, 1);
+ animation-play-state: paused;
+}
+
+.LinkButton:hover .LinkButton-arrow {
+ animation-play-state: running;
+}
+
+@keyframes arrow-move-animation {
+ 0% {
+ transform: translateX(0px) scale(1, 1);
+ }
+ 100% {
+ transform: translateX(4px) scale(1.1, 1.1);
+ }
+}
+
+.LinkButton-arrow {
+ margin-left: 12px;
+ align-self: center;
+ margin-top: auto;
+ margin-bottom: auto;
+}
+
+.ResultCard--blue,
+.ResultCard--blue * {
+ --result__background-color: #0017e9;
+ --result__primary-color: var(--color-brand);
+ --result__foreground-color: white;
+ --result__muted-color: rgb(165, 165, 165);
+}
+
+.ResultCard {
+ padding: 16px;
+ max-width: var(--card-width);
+
+ display: grid;
+ grid-template-rows: 1fr auto 1fr;
+ grid-template-columns: auto;
+ grid-row-gap: 16px;
+
+ background-color: var(--result__background-color);
+ color: var(--result__foreground-color);
+}
+
+.ResultCard-title {
+ font-size: 1rem;
+ font-weight: bold;
+ font-family: var(--body-font);
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ max-width: 100%;
+}
+
+.ResultList {
+ display: grid;
+ grid-row-gap: 8px;
+}
+
+.ResultListItem-name {
+ font-weight: bold;
+ white-space: nowrap;
+}
+
+.ResultListItem-progressContainer {
+ display: block;
+ width: auto;
+ margin-top: auto;
+ margin-bottom: auto;
+ height: 2px;
+ content: "";
+}
+
+.ResultListItem-progressValue {
+ background-color: var(--result__foreground-color);
+ height: 2px;
+ content: "";
+ display: block;
+}
+
+.ResultListItem--fastest .ResultListItem-name {
+ color: var(--result__primary-color);
+}
+
+.ResultListItem--fastest .ResultListItem-progressValue {
+ background-color: var(--result__primary-color);
+}
+
+.ResultListItem--slowest .ResultListItem-progressValue {
+ background-color: var(--result__muted-color);
+}
+
+.ResultListItem--slowest .ResultListItem-name {
+ color: var(--result__muted-color);
+}
+
+.ResultListItem {
+ grid-template-columns: 100px 100px;
+ display: grid;
+ grid-column-gap: 6px;
+}
+
+.ListContainer {
+ display: flex;
+}
+
+.ScoreContainer {
+ margin-right: 26px;
+}
+
+.Score {
+ color: var(--result__primary-color);
+ font-size: 2rem;
+ font-weight: bold;
+ font-family: var(--heading-font);
+}
+
+.Operations {
+ color: var(--result__muted-color);
+ font-size: 1rem;
+}
+
+.ResultCard-link {
+ display: flex;
+ align-items: center;
+ font-weight: bold;
+ text-transform: uppercase;
+}
+.ResultCard-linkArrow {
+ margin-left: 6px;
+}
+
+.Confetti {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ transform: translate(25vh, 10vw);
+ overflow: hidden;
+ pointer-events: none;
+ user-select: none;
+ webkit-user-select: none;
+}
+
+.ShareSheet,
+.ResultListSection,
+.BenchmarkHeader,
+.SnippetList,
+.CodeEditor {
+ width: var(--page-width);
+ padding: 0px var(--padding-horizontal);
+ margin: 0 auto;
+}
+
+.BenchmarkHeader {
+ display: flex;
+ align-items: center;
+}
+
+.TitleInput-container {
+ display: flex;
+ flex: 1;
+ width: 100%;
+}
+
+.TitleInput {
+ background-color: transparent;
+ appearance: none;
+ -webkit-appearance: none;
+ font-size: 2.5rem;
+ box-shadow: none;
+ outline: 0;
+
+ border: 0;
+ width: 100%;
+ margin-right: 32px;
+ font-family: var(--heading-font);
+ border-bottom: 1px solid transparent;
+ color: white;
+ transition: all 0.2s ease;
+}
+
+.TitleInput-container--readOnly .TitleInput,
+.TitleInput-container--readOnly .TitleInput:hover {
+ cursor: pointer;
+}
+.TitleInput-container--readWrite .TitleInput:hover {
+ background: rgba(255, 255, 255, 0.1);
+}
+
+.TitleInput-container--readWrite .TitleInput:focus {
+ background: rgba(255, 255, 255, 0.1);
+}
+
+.TitleInput,
+.SnippetTitle {
+ text-transform: none;
+}
+
+.SnippetTitle[disabled] {
+ background-color: transparent;
+}
+
+.SnippetTitle,
+.NewSnippetContainer-label {
+ background: transparent;
+ display: block;
+ flex: 1;
+ appearance: none;
+ -webkit-appearance: none;
+
+ color: white;
+ font-family: var(--heading-font);
+ font-weight: 400;
+ height: 100%;
+ padding: 16px 12px;
+ margin: 0;
+ border: 0;
+ box-shadow: none;
+}
+
+.NewSnippetContainer,
+.SnippetContainer *,
+.SnippetContainer {
+ --snippets_container-background: var(
+ --snippets_container-background-unfocused
+ );
+}
+
+.SnippetContainer--isRunning {
+ overflow: hidden;
+}
+
+.SnippetContainer {
+ position: relative;
+}
+
+.SnippetContainer-ErrorTitle {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: #fe0100;
+ padding: 6px 14px;
+
+ font-size: 0.8rem;
+ color: #ffffff;
+ font-weight: 500;
+ font-family: var(--heading-font);
+}
+
+.SnippetContainer .SnippetOverlay,
+.SnippetContainer .SnippetBackground {
+ display: none;
+}
+
+.SnippetBackground {
+ position: absolute;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ right: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 999;
+ mix-blend-mode: difference;
+ -webkit-user-select: none;
+ user-select: none;
+ pointer-events: none;
+ height: 100%;
+ transform-origin: left;
+ transform: scaleX(0);
+ content: "";
+ background-color: var(--color-brand);
+ transition: transform 0.12s linear;
+ transition-property: opacity, transform;
+}
+
+.SnippetOverlay {
+ position: absolute;
+
+ left: 24px;
+ top: 50%;
+ transform: translateY(-50%);
+
+ z-index: 1;
+ -webkit-user-select: none;
+ user-select: none;
+ flex-direction: column;
+ justify-content: flex-start;
+ font-family: var(--heading-font);
+
+ pointer-events: none;
+ color: white;
+}
+
+/* .SnippetContainer--isRunning .SnippetOverlay {
+ transform: translateX(16px) translateY(100%) translateY(-2rem)
+ translateY(-32px);
+} */
+
+.SnippetOverlayLabel {
+ font-size: 2rem;
+
+ transition: filter 0.12s linear;
+ transition-property: filter, color;
+}
+
+.CodeContainer {
+ filter: blur(0px);
+ transition: filter 0.12s linear;
+}
+
+.SnippetContainer--ran .CodeContainer {
+ filter: none;
+}
+
+.SnippetContainer--ran .SnippetOverlayLabel {
+ filter: none;
+ color: var(--color-brand);
+}
+
+.SnippetOverlayLabel-ops {
+}
+
+.SnippetContainer--ran .SnippetOverlay,
+.SnippetContainer--isRunning .SnippetOverlay {
+ display: flex;
+}
+
+.SnippetContainer--ran .SnippetBackground {
+ opacity: 0;
+}
+
+.SnippetContainer--ran .SnippetBackground,
+.SnippetContainer--isRunning .SnippetBackground {
+ display: block;
+}
+
+.NewSnippetContainer,
+.SnippetContainer {
+ transition: background-color 0.1s linear;
+}
+
+.SnippetIcon {
+ display: flex;
+ user-select: none;
+ -webkit-user-select: none;
+ margin-right: 6px;
+ margin-left: auto;
+}
+
+.SnippetIndexIcon,
+.SnippetRank {
+ text-transform: uppercase;
+ font-family: var(--heading-font);
+ font-size: 1.1rem;
+ text-align: left;
+ margin-left: 21px;
+ margin-right: 1ch;
+ opacity: 0.5;
+}
+
+.SnippetRank--first {
+ color: var(--color-brand);
+}
+
+.NewSnippetContainer:hover,
+.SnippetContainer:hover *,
+.SnippetContainer:hover {
+ --snippets_container-background: var(--snippets_container-background-focused);
+}
+
+.NewSnippetContainer,
+.SnippetTitleContainer {
+ display: grid;
+ flex: 1;
+ grid-template-columns: 42px auto;
+
+ align-items: center;
+ grid-column-gap: 0;
+ position: relative;
+}
+
+.SnippetContainer-ErrorClose,
+.SnippetTitle-deleteButton {
+ --color: rgb(153, 153, 153);
+ --active-color: rgb(189, 58, 58);
+}
+
+.SnippetTitle-deleteButton {
+ position: absolute;
+ right: 0;
+}
+
+.SnippetTitle-importButtonContainer {
+ position: absolute;
+ right: 0;
+ display: grid;
+ grid-auto-flow: column;
+ grid-column-gap: 16px;
+ align-items: center;
+ z-index: 10;
+}
+
+.SnippetTitle-transformField {
+ display: flex;
+ cursor: pointer;
+ align-items: center;
+ transition: transform 0.1s linear;
+}
+
+.SnippetTitle-transformField:hover {
+ transform: scale(1.05, 1.05);
+}
+
+.SnippetTitle-transformField:active {
+ transform: scale(1.2, 1.2);
+}
+
+.Toggler {
+ width: 16px;
+ height: 16px;
+ border-radius: 0;
+ border: 2px solid rgba(255, 255, 255, 0.3);
+ margin-right: 6px;
+}
+
+.SnippetTitle-transformField--checked .Toggler {
+ background-color: var(--color-brand);
+ border-color: rgb(50, 50, 50);
+}
+.SnippetTitle-transformField-label {
+ text-transform: uppercase;
+ margin-left: 4px;
+ user-select: none;
+ -webkit-user-select: none;
+ color: white;
+ font-family: var(--heading-font);
+}
+
+.SnippetTitle-transformField--checked .SnippetTitle-transformField-label {
+ color: var(--color-brand);
+}
+
+.SnippetContainer-ErrorClose,
+.SnippetTitle-transformField,
+.SnippetTitle-deleteButton,
+.SnippetTitle-importButton {
+ font-weight: 500;
+ font-size: 0.8rem;
+ font-family: var(--heading-font);
+
+ color: var(--color);
+ padding-right: 16px;
+ cursor: pointer;
+ pointer-events: all;
+ transition: transform 0.1s linear;
+ transition-property: transform, color;
+}
+
+.SnippetContainer-ErrorClose {
+ --translate-offset: -50%;
+ color: white;
+ position: absolute;
+ top: 50%;
+ transform: translateY(var(--translate-offset));
+ right: 0;
+}
+
+.SnippetTitle-importButton {
+ --color: white;
+ --active-color: var(--color-brand);
+}
+
+.SnippetContainer-ErrorClose:hover,
+.SnippetTitle-importButton:hover,
+.SnippetTitle-deleteButton:hover {
+ transform: translateY(var(--translate-offset, 0%)) scale(1.1, 1.1);
+ color: var(--active-color);
+}
+
+.SnippetContainer-ErrorClose:active,
+.SnippetTitle-importButton:active,
+.SnippetTitle-deleteButton:active {
+ transform: translateY(var(--translate-offset, 0%)) scale(1.2, 1.2);
+ color: var(--active-color);
+}
+
+.SnippetContainer-ErrorClose:hover,
+.SnippetContainer-ErrorClose:active {
+ color: white;
+}
+.SnippetTitleContainer {
+ position: relative;
+ z-index: 10;
+}
+
+.ShareHeader {
+ font-family: var(--heading-font);
+ font-size: 1.5rem;
+ color: white;
+ user-select: none;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+}
+
+.ShareSheet {
+ display: grid;
+
+ grid-template-columns: max-content;
+ margin-bottom: 24px;
+ user-select: none;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+}
+
+.ShareHeader-copyButton {
+ margin-top: auto;
+ margin-bottom: auto;
+
+ font-family: var(--heading-font);
+ color: white;
+ transform: scale(1, 1);
+ transition: transform 0.1s linear;
+ transition-property: color, transform;
+
+ cursor: pointer;
+ user-select: none;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ padding: 0 16px;
+ display: block;
+}
+
+.ShareHeader-copyButton:hover {
+ transform: scale(1.2, 1.2);
+ color: var(--color-brand);
+}
+
+.ShareHeader-copyButton:active {
+ transform: scale(1.5, 1.5);
+ color: var(--color-brand);
+}
+
+.ShareHeader-urlBox {
+ padding: 16px 0;
+ margin: 0;
+ width: 100%;
+ overflow-x: hidden;
+ white-space: nowrap;
+}
+.ShareHeader-url {
+ font-size: 1rem;
+ user-select: auto;
+ --webkit-user-select: auto;
+ margin: 0;
+ min-width: 480px;
+ max-width: var(--page-width);
+ border-radius: 0;
+ border: 1px solid rgb(32, 32, 32);
+ flex: 1;
+ color: rgb(220, 220, 220);
+ appearance: none;
+ background-color: rgba(255, 255, 255, 0.1);
+ box-shadow: none;
+ font-family: var(--heading-font);
+ font-variant-ligatures: none;
+ padding: 8px 16px;
+ width: 100%;
+ outline: 0;
+ transition: all 0.2s ease;
+}
+
+.ShareHeader-urlBox {
+ display: flex;
+}
+
+.ShareHeader-url:hover {
+ background: rgba(255, 255, 255, 0.15);
+}
+
+@media (max-width: 1152px) {
+ :root {
+ --page-width: 800px;
+ --padding-horizontal: 24px;
+ }
+}
+
+@media (max-width: 800px) {
+ :root {
+ --page-width: 100%;
+ --padding-horizontal: 24px;
+ }
+
+ .Hero-demo {
+ display: none;
+ }
+}
+
+@media (max-width: 600px) {
+ :root {
+ --card-width: 100%;
+ }
+}
+
+.NewSnippetContainer,
+.SnippetContainer {
+ background-color: var(--snippets_container-background);
+}
+
+.SnippetContainer--isRunning {
+ background-color: var(--snippets_container-background-unfocused);
+}
+
+.SnippetContainer--isRunning .CodeContainer {
+ opacity: 0.5;
+}
+
+.NewSnippetContainer {
+ cursor: pointer;
+ transition: all 0.2s ease;
+ opacity: 0.7;
+}
+
+.NewSnippetContainer:hover {
+ opacity: 1;
+}
+
+.SnippetHeading-subheader {
+ display: grid;
+ grid-template-columns: auto auto auto auto auto;
+ grid-column-gap: 6px;
+ text-transform: uppercase;
+ letter-spacing: 1.35px;
+ padding-left: 54px;
+ margin-top: -12px;
+ color: inherit;
+ padding-bottom: 16px;
+}
+
+.SnipptHeading-Dot {
+}
+
+.xIcon {
+ text-transform: lowercase;
+}
+
+.SnippetHeading--first {
+ color: var(--color-brand);
+}
+
+.SnippetHeading--notFirst {
+ color: rgb(153, 153, 153);
+}
+
+.ResultListSection {
+}
+
+.ResultListSection {
+ margin-bottom: 1rem;
+}
+.ResultListSection--heading {
+ font-size: 1.5rem;
+ color: white;
+ font-family: var(--heading-font);
+}
+
+a.ResultListSection--subHeading-section {
+ cursor: pointer;
+}
+
+a.ResultListSection--subHeading-section:hover {
+ text-decoration: underline;
+}
+
+.ResultListSection--disabled {
+ opacity: 0.5;
+}
+.ResultListSection--subHeading {
+ color: rgb(153, 153, 153);
+ display: grid;
+ width: 100%;
+ grid-auto-flow: column;
+ grid-auto-columns: min-content;
+ white-space: nowrap;
+
+ grid-column-gap: 8px;
+ margin-bottom: 16px;
+}
+.ResultListSection--subHeading--section {
+ white-space: nowrap;
+ display: block;
+}
+.ResultListSection--subHeading--separator {
+}
+.ResultListSection--results {
+ display: grid;
+ grid-row-gap: 20px;
+}
+
+.ResultLongListItem--notFirst {
+ color: white;
+}
+
+.ResultLongListItem--first {
+ color: var(--color-brand);
+}
+
+.ResultLongListItem--first {
+}
+.ResultLongListItem--notFirst {
+}
+.ResultLongListItem-line {
+ display: flex;
+}
+
+.ResultLongListItem {
+ margin-bottom: 24px;
+}
+.ResultLongListItem-name {
+ color: rgb(153, 153, 153);
+}
+
+.ResultLongListItem--first .ResultLongListItem-name,
+.ResultLongListItem--first .ResultLongListItem-progressBar {
+ color: var(--color-brand);
+}
+
+.ResultLongListItem-multiplier {
+}
+.ResultLongListItem-progressBarContainer {
+ margin-top: auto;
+ margin-bottom: auto;
+}
+.ResultLongListItem-progressBar {
+}
+.ResultLongListItem-statGroup {
+ display: grid;
+ width: 400px;
+ max-width: var(--page-width);
+ grid-template-columns: 300px 100px;
+ grid-column-gap: 0;
+ align-items: center;
+
+ font-size: 2rem;
+ white-space: nowrap;
+ padding-right: 28px;
+}
+
+.ResultLongListItem-progressBar,
+.ResultLongListItem-progressBarContainer {
+ height: 3px;
+ content: "";
+}
+
+.ResultLongListItem-progressBar {
+ background-color: currentColor;
+}
+
+.ResultLongListItem-progressBarContainer {
+ width: 100%;
+}
+
+@media (max-width: 600px) {
+ .ResultLongListItem-statGroup {
+ grid-template-columns: 200px 100px;
+ }
+
+ .ResultLonglistItem {
+ margin-top: 12px;
+ }
+
+ .ResultLongListItem-line {
+ flex-direction: column;
+ }
+
+ .ResultLongListItem-statGroup {
+ margin-bottom: 12px;
+ }
+
+ .ShareHeader-urlBox {
+ display: none;
+ }
+}
+
+.GithubLink {
+ font-size: 0.8rem;
+ padding: 4px;
+ display: block;
+ color: rgb(153, 153, 153);
+}
+
+.ModuleListContainer {
+ max-height: 400px;
+ overflow-y: scroll;
+ max-height: 400px;
+ min-height: 200px;
+}
+
+.ModulePickerModal {
+ position: absolute;
+
+ background: linear-gradient(
+ 136.61deg,
+ rgb(39, 40, 43) 13.72%,
+ rgb(45, 46, 49) 74.3%
+ );
+ backdrop-filter: blur(12px);
+ color: white;
+ z-index: 9999999;
+ max-height: 400px;
+ min-height: 200px;
+ overflow: hidden;
+ pointer-events: all;
+
+ border-radius: 8px;
+ box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 24px;
+}
+
+.SnippetContainer--unposition .SnippetTitle-deleteButton {
+ display: none;
+}
+.SnippetContainer--unposition .SnippetTitleContainer {
+ position: static;
+}
+
+.ModuleListContainer-empty {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ min-height: 100%;
+ height: 100%;
+ flex: 1;
+ padding-left: 12px;
+ margin-top: 12px;
+}
+
+.ModuleListContainer-emptyText {
+}
+
+.ModuleListContainer-emptyText-muted {
+ color: var(--result__muted-color);
+ opacity: 0.5;
+ margin-top: 4px;
+}
+
+.ModulePicker-search {
+ width: 100%;
+ display: flex;
+ flex: 0 0 48px;
+ background-color: rgb(32, 32, 32);
+ color: white;
+ font-family: var(--heading-font);
+ font-size: 1rem;
+ outline: none;
+ box-shadow: none;
+ -webkit-appearance: none;
+ appearance: none;
+ border: 0;
+ padding-left: 12px;
+ padding-right: 12px;
+}
+
+.ModulePicker {
+ display: flex;
+ flex-direction: column;
+ width: 400px;
+}
+
+.ModuleListItem {
+ display: flex;
+ justify-content: space-between;
+ padding: 8px 12px;
+ cursor: pointer;
+ background-color: transparent;
+ transform: background-color 0.2s ease;
+}
+
+.ModuleListItem:hover {
+ background-color: rgba(255, 255, 255, 0.05);
+}
+
+.ModuleListItem-info {
+ display: grid;
+ grid-template-rows: min-content min-content;
+ font-variant-ligatures: none;
+ grid-row-gap: 2px;
+}
+
+.ModuleListItem-name {
+ color: rgba(255, 255, 255, 0.8);
+ font-family: var(--heading-font);
+ font-size: 0.9rem;
+}
+
+.ModuleListItem-description {
+ color: rgba(255, 255, 255, 0.5);
+ font-size: 0.9rem;
+}
+
+.ModuleListItem-description,
+.ModuleListItem-name {
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ width: 280px;
+}
+
+.ModuleListItem:hover .ModuleListItem-importButton {
+ opacity: 1;
+}
+.ModuleListItem-importButton {
+ text-transform: uppercase;
+ margin-top: auto;
+ margin-bottom: auto;
+ font-family: var(--heading-font);
+ font-weight: bold;
+ color: var(--color-brand);
+ padding: 4px 6px;
+ margin-left: 8px;
+ letter-spacing: 0.05rem;
+ font-size: 0.9rem;
+ transition: all 0.2s ease;
+ opacity: 0;
+}
+
+.BenchmarkHeader--mobile {
+ display: none;
+}
+@media (max-width: 600px) {
+ :root {
+ --padding-horizontal: 16px;
+ }
+
+ .BenchmarkHeader--mobile {
+ display: flex;
+ }
+ .BenchmarkHeader--desktop {
+ display: none;
+ }
+
+ .ResultListSection--subHeading-separator {
+ display: none;
+ }
+
+ .ResultListSection--subHeading {
+ grid-auto-flow: row;
+ white-space: normal;
+ grid-auto-columns: auto;
+ --page-width: auto;
+ }
+
+ .ResultLongListItem-statGroup {
+ display: flex;
+ max-width: 100%;
+ width: auto;
+ justify-content: space-between;
+ padding-right: var(--padding-horizontal);
+ }
+
+ .CodeContainer {
+ zoom: 0.8;
+ }
+
+ .BenchmarkHeader {
+ flex-direction: column;
+ }
+}
+
+.ShareSheet-image-loading {
+ animation: fade-in-out 1.5s ease;
+ transform: scale(2);
+ transform-origin: center center;
+ animation-iteration-count: infinite;
+ animation-direction: alternate-reverse;
+}
+
+@keyframes fade-in-out {
+ 0% {
+ opacity: 1;
+ }
+ 50% {
+ opacity: 0.66;
+ }
+ 100% {
+ opacity: 1;
+ }
+}
diff --git a/src/test/fixtures/test-import.css b/src/test/fixtures/test-import.css
new file mode 100644
index 000000000..4fecc3135
--- /dev/null
+++ b/src/test/fixtures/test-import.css
@@ -0,0 +1,3 @@
+.bacon {
+ display: block;
+}