You are working in `/workspace/typescript`, a source tree checked out at the base commit for this task. Implement the requested behavior in the source tree, then run: ```bash lolbench-submit ``` Do not stop after editing files, running tests, or describing the solution. The task is complete only when `lolbench-submit` has created `/logs/artifacts/solution.patch`. If that file does not exist, continue working and run `lolbench-submit` again. That command writes your implementation diff to `/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier will grade. Before running `lolbench-submit`, clean or revert any test files you created or modified; test files must not be included in the final `solution.patch`. This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. Now please implement the following requirements in the source tree: --- # Deferring Module Evaluation previously known as "Lazy Module Initialization" ## Background JS applications can get very large, to the point that not only loading, but even executing their initialization scripts incurs a significant performance cost. Usually, this happens later in an application's life span - often requiring invasive changes to make it more performant. Loading performance is a big and important area for improvement, and involves preloading techniques for avoiding waterfalls and dynamic `import()` for lazily loading modules. But even with loading performance solved using these techniques, there is still overhead for execution performance - CPU bottlenecks during initialization due to the way that the code itself is written. ## Motivation Avoiding unnecessary execution is a well-known optimization in the Node.js CommonJS module system, where there is a smaller gap between load contention and execution contention. The common pattern in Node.js applications is to refactor code to dynamically require as needed: ```js const operation = require('operation'); exports.doSomething = function (target) { return operation(target); } ``` being rewritten as a performance optimization into: ```js exports.doSomething = function (target) { const operation = require('operation'); return operation(target); } ``` The consumer still is provided with the same API, but with a more efficient use of FS & CPU during initialization time. For ES modules, we have a solution for the lazy loading component of this problem via dynamic `import()`. For the same example we can write: ```js export async function doSomething (target) { const { operation } = await import('operations'); return operation(target); } ``` This avoids bottlenecking the network and CPU during application initialization, but there are still a number of problems with this technique: 1. It doesn't actually solve the deferral of execution problem, since sending a network request in such a scenario would usually be a performance regression and not an improvement. A separate network preloading step would therefore still be desirable to achieve efficient deferred execution while avoiding triggering a waterfall of requests. 2. It forces all functions and their callers into an asynchronous programming model, without necessarily reflecting the real intention of the program. This leads to all call sites having to be updated into a new model, and cannot be made without a breaking API change to existing API consumers. ## Problem Statement Deferring the synchronous evaluation of a module may be desirable new primitive to avoid unnecessary CPU work during application initialization, without requiring any changes from a module API consumer perspective. Dynamic import does not properly solve this problem, since it must often be coupled with a preload step, and enforces the unnecessary asyncification of all functions, without providing the ability to only defer the synchronous evaluation work. ## Proposal The proposal is to have a new syntactical import form which will only ever return a namespace exotic object. When used, the module and its dependencies would not be executed, but would be fully loaded to the point of being execution-ready before the module graph is considered loaded. _Only when accessing a property of this module, would the execution operations be performed (if needed)._ This way, the module namespace exotic object acts like a proxy to the evaluation of the module, effectively with [[Get]] behavior that triggers synchronous evaluation before returning the defined bindings. The API will use the below syntax, following the phases model established by the [source phase imports](https://github.com/tc39/proposal-source-phase-imports) proposal: ```js // or with a custom keyword: import defer * as yNamespace from "y"; ``` This namespace binding is the only form a deferred import may take. Because `import defer` can only ever produce a namespace exotic object, a default binding (`import defer someDefault from "y"`) or named bindings (`import defer { thing } from "y"`) carry no meaning and are rejected at compile time. A default binding produces error `TS18058`, "Default imports are not allowed in a deferred import." Named bindings produce error `TS18059`, "Named imports are not allowed in a deferred import." Deferred imports are furthermore supported only under module targets that preserve native ES import syntax. A deferred import is accepted only when the `--module` flag is set to `esnext` or `preserve`; under every other target, including `commonjs`, `es2015`, `es2020`, and `nodenext`, the compiler reports error `TS18060`, "Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'." Deferring also has a dynamic counterpart, mirroring the `import.` call form of the source phase imports proposal described below. Calling `import.defer(specifier)` performs a dynamic deferred import and evaluates to a promise for the deferred namespace, so that `import.defer("./dep.js")` has type `Promise`. Here `import.defer` is a meta-property (alongside `import.meta`) that must be _immediately_ called: a bare reference such as `const callee = import.defer;`, a parenthesized callee such as `(import.defer)("./dep.js")`, or passing `import.defer` as an argument to another call are all syntax errors, each reported as error `TS1005`, "'(' expected." Any meta-property name on `import` other than `meta` or `defer` is reported with error `TS18061`. The same `esnext`/`preserve` module restriction (error `TS18060`) also applies to the `import.defer(...)` dynamic call form. ## Semantics The imports would still participate in deep graph loading so that they are fully populated into the module cache prior to execution, however it the imported module will not be evaluated yet. When a property of the resulting module namespace object is accessed, if the execution has not already been performed, a new top-level execution would be initiated for that module. In this way, a deferred module evaluation import acts as a new top-level execution node in the execution graph, just like a dynamic import does, except executing synchronously. There are possible extensions under consideration, such as deferred re-exports, but they are not included in the current version of the proposal. ### Top-level await Property access on the namespace object of a deferred module must be synchronous, and it's thus impossible to defer evaluation of modules that use top-level await. When a module is imported using the `import defer` syntax, its asynchronous dependencies together with their own transitive dependencies are eagerly evaluated, and only the synchronous parts of the graph are deferred. Consider the following example, where `a` is the top-level entry point:
```js // a import "b"; import defer * as c from "c" setTimeout(() => { c.value }, 1000); ``` ```js // b ``` ```js // c import "d" import "f" export let value = 2; ```
```js // d import "e" await 0; ``` ```js // e ``` ```js // f ```
Since `d` uses top-level await, `d` and its dependencies cannot be deferred: - The initial evaluation will execute `b`, `e`, `d` and `a`. - Later, the `c.value` access will trigger the execution of `f` and `c`. ### Rough sketch If we split out the components of Module loading and initialization, we could roughly sketch out the intended semantics: > ⚠️ The following example does not take cycles into account ```js // LazyModuleLoader.js async function loadModuleAndDependencies(name) { const loadedModule = await import.load(`./${name}.js`); // load is async, and needs to be awaited const parsedModule = loadedModule.parse(); await Promise.all(parsedModule.imports.map(loadModuleAndDependencies)); // load all dependencies return parsedModule; } async function executeAsyncSubgraphs(module) { if (module.hasTLA) return module.evaluate(); return Promise.all(module.importedModules.map(executeAsyncSubgraphs)); } export default async function lazyModule(object, name) { const module = await loadModuleAndDependencies(name); await executeAsyncSubgraphs(module); Object.defineProperty(object, name, { get: function() { delete object[name]; const value = module.evaluateSync(); Object.defineProperty(object, name, { value, writable: true, configurable: true, enumerable: true, }); return value; }, configurable: true, enumerable: true, }); return object; } // myModule.js import foo from "./bar"; etc. // module.js import LazyModule from "./LazyModuleLoader"; await LazyModule(globalThis, "myModule"); function Foo() { myModule.doWork() // first use } ``` ## Implementations - engine262: https://github.com/nicolo-ribaudo/engine262/tree/defer-eval - webpack: https://github.com/webpack/webpack/pull/16567 - Babel: https://babeljs.io/docs/babel-plugin-proposal-import-defer ## Q&A #### What happened to the direct lazy bindings? The initial version of this proposal included direct binding access for deferred evaluation via named exports: ```js import { feature } from './lib' with { lazyInit: true } export function doSomething (param) { return feature(param); } ``` where the deferred evaluation would only happen on _access_ of the `feature` binding. There are a number of complexities to this approach, as it introduces a novel type of execution point in the language, which would need to be worked through. This approach may still be investigated in various ways within this proposal or an extension of it, but by focusing on the module namespace exotic object approach first, it keeps the semantics simple and in-line with standard JS techniques. #### Is there really a benefit to optimizing execution, when surely loading is the bottleneck? While it is true that loading time is the most dominant factor on the web, it is important to consider that many large applications can block the CPU for of the range of 100ms while initializing the main application graph. Loading times of the order of multiple seconds often take the focus for performance optimization work, and this is certainly an important problem space, but the problem of freeing up the main event loop during initialization remains a critical one when the network problem is solved, that doesn't currently have any easy solutions today for large applications. #### Is there prior art for this in other languages? The standard libraries of these programming languages includes related functionality: - Ruby's `autoload`, in contrast with `require` which works in the same way as JS `import` - Clojure `import` - Most LISP environments Our approach is pretty similar to the Emacs Lisp approach, and it's clear from a manual analysis of billions of Stack Overflow posts that this is the most straightforward to ordinary developers. #### Why not support a synchronous evaluation API on ModuleInstance A synchronous evaluation API on the module expression and compartments [ModuleInstance](https://github.com/tc39/proposal-compartments/blob/master/0-module-and-module-source.md#module-instances) object could offer an API for synchronous evaluation of modules, which could be compatible with this approach of deferred evaluation, but it is only in having a clear syntactical solution for this use case, that it can be supported across dependency boundaries and in bundlers to bring the full benefits of avoiding unnecessary initialization work to the wider JS ecosystem. #### What can we do in current JS to approximate this behavior? The closest we can get is the following: ```js // moduleWrapper.js export default function ModuleWrapper(object, name, lambda) { Object.defineProperty(object, name, { get: function() { // Redefine this accessor property as a data property. // Delete it first, to rule out "too much recursion" in case object is // a proxy whose defineProperty handler might unwittingly trigger this // getter again. delete object[name]; const value = lambda.apply(object); Object.defineProperty(object, name, { value, writable: true, configurable: true, enumerable: true, }); return value; }, configurable: true, enumerable: true, }); return object; } // module.js import ModuleWrapper from "./ModuleWrapper"; // any imports would need to be wrapped as well function MyModule() { // ... all of the work of the module } export default ModuleWrapper({}, "MyModule", MyModule); // parent.js import wrappedModule from "./module"; function Foo() { wrappedModule.MyModule.bar() // first use } ``` However, this solution doesn't cover deferring the loading of submodules of a lazy graph, and would not acheive the characteristics we are looking for. #### Why `import defer *` gives a different namespace object from `import *`? Module namespace objects of modules that are _already evaluated_ and threw during evaluation do not re-throw an error on property access: ```js // module-that-throws1 import * as self from 'module-that-throws1'; globalThis.ns1 = self; export let a = 1; throw new Error("oops"); ``` ```js // main1.js import("module-that-throws1").finally(() => { console.log(globalThis.ns1.a); // Doesn't throw, logs '1' }); ``` Deferred namespaces are different. If the module throws while being evaluated, `deferredNamespace.foo` will always throw the evaluation error: ```js // module-that-throws2 export let a = 1; throw new Error("oops"); ``` ```js // main2.js import defer * as ns2 from 'module-that-throws2'; try { ns2.a } catch (e) { console.log(e.message) } // logs "oops" ``` Before this proposal having access to a namespace object of a module that threw during evaluation is incredibly rare. However, it becomes more common with `import defer` declarations. The `import defer` in `main2.js` would have a race condition if it errored only when `module-that-throws2` has already been loaded by something else, instead the error will always be deffered until the namespace is accessed. As `ns2.a` must throw even if `module-that-throws2` is already evaluated, and thus it cannot be the same namespace object as `import *`. Another approach we considered (and discarded) was to always suppress evaluation errors on namespace property access, so that in the example above `ns2.a` would be guaranteed to _never_ throw and thus not be affected by unrelated modules that might have already triggered evaluation of `module-that-throws`. #### Why not re-use import attributes (`import * as ns from "mod" with { defer: true }`)? There are two reasons why we chose to use an "import modifier" rather than an attribute: 1. Import attributes affect what a module _is_, but cannot change basic semantics of how ECMAScript modules behave: they are similar to adding query parameters to the imported URL, except that attributes are handled by the running environment rather than by the server. For example, `with { type: "json" }` behaves as if the imported module was a JavaScript file wrapped in ``export default JSON.parse(` ... the file contents ... `);``. `import defer` changes how namespace objects behave (by making them side-effectul, while before this proposal property access on namespace objects couldn't trigger any side effect): it cannot be expressed as a wrapped/modified "classic" ECMAScript module. 2. Together with the [source phase imports proposal](https://github.com/tc39/proposal-source-phase-imports), we are exposing multiple "phases" of module loading. The phases we've identified are: resolving a module given a specifier, fetching the module (these two both happens in hosts and not in ECMA-262), attaching modules to their execution and resolution context, linking modules together, and finally executing them. We are using `import` modifiers to represent modules processed up to one of those phases, without going all the way to finishing execution. These modifiers give more guarantees than import attributes: while `import "x" with { attr1: "val" }` and `import "x" with { attr2: "val2" }` might be two completely different modules, `import source s from "x"`, `import defer * as ns from "x"`, and `import "x"` all are guaranteed to load the same module, and that module will be executed at most once regardless of which "phase" it gets temporarely paused at (and then continued from). ## Linked Proposal — Source Phase Imports ## Motivation For both JavaScript and WebAssembly, there is a need to be able to more closely customize the loading, linking, and execution of modules beyond the standard host execution model. For JavaScript, creating userland loaders would require a module source type in order to share the host parsing, execution, security, and caching semantics. For WebAssembly, imports and exports for WebAssembly modules often require custom inspection and wrapping in order to be set up correctly, which typically requires manual fetch and instantiation work that is not provided for in the current host [ESM integration][wasm-esm] proposal. Supporting syntactical module source imports as a new import phase creates a primitive that can extend the static, security and tooling benefits of modules from the ESM integration to these dynamic instantiation use cases. ## Proposal This proposal allows ES modules to import a reified representation of the compiled source of a module when the host provides such a representation: ```js import source x from ""; ``` The `source` module source loading phase name is added to the beginning of the ImportStatement. Only the above form is supported - named exports and unbound declarations are not supported. ### Dynamic form Just as with static and dynamic imports, there is a need for static and dynamic access to sources, to be able to support both those sources that are required to be instantiated from source text during initialization of an application, and those that are optionally or lazily created at runtime. The dynamic form uses a `import.` import call: ```js const x = await import.source(""); ``` By making the phase part of the explicit syntax, it is possible to statically distinguish between a full dynamic import and one that is only for a source (where dependencies don't need to be processed). Optional [import attributes][] may still be specified with the second argument in a `with` key, just like for dynamic import, and without conflict due to the design of phased evaluation. ### Loading Phase Module source imports can be seen to be one type of evaluation phase. If the [asset references proposal][] advances in future this could be seen as another type of phase representing an earlier phase of the loading process. ```js import asset x from ""; await import.asset(""); ``` Only the `source` import source phase is specified by this proposal. ### Defining Module Source The object provided by the module source phase must be an object with `AbstractModuleSource.prototype` in its prototype chain, defined by this specification to be a minimal shared base prototype for a compiled modular resource. In addition it defines the `@@toStringTag` getter returning the constructor name string corresponding to the name of the specific module source subclass, with a strong internal slot check. ### JS Module Source For JavaScript modules, the module source phase is then specified to return a `ModuleSource` object, representing an ECMAScript Module Source, where `ModuleSource.prototype.[[Proto]]` is `%AbstractModuleSource%.prototype`. Future proposals may then add support for [bindings lookup methods][], the [ModuleSource constructor][module soruce] and [instantiation][] support. New properties may be added to the base `%AbstractModuleSource%.prototype`, or shared with ECMAScript module sources via `ModuleSource.prototype` additions. ### Wasm Module Source For WebAssembly modules, the existing `WebAssembly.Module.prototype` object is to be updated to have a `[[Proto]]` of `%AbstractModuleSource%.prototype` in the [WebAssembly JS integration API][wasm-js-api]. This allows workflows, as explained in the motivation, like the following: ```js import source FooModule from "./foo.wasm"; FooModule instanceof WebAssembly.Module; // true // For example, to run a WASI execution with an API like Node.js WASI: import { WASI } from 'wasi'; const wasi = new WASI({ args, env, preopens }); const fooInstance = await WebAssembly.instantiate(FooModule, { wasi_snapshot_preview1: wasi.wasiImport }); wasi.start(fooInstance); ``` The static analysis benefits of not needing a custom `fetch` and `WebAssembly.compileStreaming` apply not only to code analysis and security but also for bundlers. In turn this enables [Wasm components to be able to import][] `WebAssembly.Module` objects themselves in future. ### Other Module Types Any other host-defined module types may define their own host module sources. If a given module does not define a source representation for it's source, importing it with a "source" phase target fails with a `ReferenceError` at link time. Host-defined module sources must include `%AbstractModuleSource%.prototype` in their prototype chain and support the `[[ModuleSourceRecord]]` internal slot containing the `@@toStringTag` brand check and underlying source host data. ## Security Benefits The native ES module loader is able to implement security policies, including support for [Content Security Policies][CSP] in browsers. This property does not just impact platforms using CSP, but also other platforms with systems to restrict permissions, such as Deno. These policies are based on protecting which URLs are supported for the compilation and execution of scripts or modules. Extending the static security benefits of the host module system to custom loaders is a security benefit of this proposal. For Wasm, it would enable source-specific CSP policies for dynamic Wasm instantiation. ## Cache Key Semantics Because `[[ModuleSourceObject]]` is keyed on the base module record, it will always be unique to the module being imported from. ## Q&A **Q**: How does this relate to import attributes? **A**: Import attributes are properties of the module request, while source imports represent phases of that specific request / key in the module map, without affecting the idempotency of the module load. Both can be used together for a resource to indicate alternative phasing for the given module resource and attributes. **Q**: How does this relate to module expressions and compartments? **A**: The module object that is provided has been carefully specified here to be compatible with the linking model of module expressions and compartments. **Q**: Why not just use `const module = await WebAssembly.compileStreaming(fetch(new URL("./module.wasm", import.meta.url)));`? **A**: There are multiple benefits: firstly if the module is statically referenced in the module graph, it is easier to statically analyze (by bundlers for example). Secondly when using CSP, `script-src: unsafe-eval` would not be needed. See the security improvements section for more details. *Source: https://github.com/tc39/proposal-source-phase-imports* ## Linked Proposal — First-class Module and ModuleSource (Module instances) ```ts type ImportSpecifier = string; type ImportHook = (this: ModuleHandler, specifier: ImportSpecifier) => Promise; type ImportMeta = { __proto__: null, // ... [name: string | symbol | number]: unknown, }; type ImportMetaHook = (this: ModuleHandler, importMeta: ImportMeta) => any; type ModuleHandler = { importHook?: ImportHook, importMetaHook?: ImportMetaHook, // ... [name: string | symbol | number]: unknown, }; interface Module { constructor( source: ModuleSource, handler: ModuleHandler, ); readonly source?: ModuleSource, } ``` Semantics: A `Module` instance has an internal ***Module Record***. Importing the module will consistently produce the same ***Module Namespace Exotic Object***. The module has a lifecycle and fresh instances have not been linked, initialized, or executed. Invoking dynamic import on a `Module` instance attempts to advance it and its transitive dependencies to their end state. Consistent with dynamic import for a stringly-named module, dynamic import on a `Module` instance produces a promise for the corresponding ***Module Namespace Exotic Object*** Dynamic import induces calls to `importHook` for each unsatisfied dependency of each module instance in separate events, before any dependency advances to the link phase of its lifecycle. Dynamic import within the evaluation of a `Module` also invokes the `importHook`. `Module` instances memoize the result of their `importHook` keyed on the given Import Specifier. `Module` constructors, like `Function` constructors, are bound to a realm and evaluate modules in their particular realm. *Source: https://github.com/tc39/proposal-compartments/blob/master/0-module-and-module-source.md#module-instances*