microsoft/qdk

Public

mirrored fromhttps://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
4c4e9d5f767314c193e5cc06ad889516c3c69b93

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

npm/README.md

97lines · modecode

1# qsharp npm module
2
3This package contains the qsharp compiler functionality shipped for consumption via npm.
4
5The source is written in TypeScript, which is compiled to ECMAScript modules in the ./dist directory.
6The wasm binaries from the Rust builds are copied to the ./lib directory.
7
8Consuming browser projects should import from this module and use a bundler to create their
9own JavaScript bundle, and also copy the wasm file to their project and provide the URL
10to it when calling the `loadWasmModule` method so it may be located and loaded.
11
12## Node and browser support
13
14wasm-pack generates different files for the browser and Node.js environments. The wasm is slightly
15different, and the loader code is quite different. This can be seen in `./lib/web/qsc_wasm.cjs`
16and `./lib/node/qsc_wasm.js` files respectively. Specifically, the web environment loads the wasm
17file using async web APIs such as `fetch` with a URI, and Node.js uses `require` to load the `fs` module
18and calls to `readFileSync`. Once the wasm module is loaded however, the exported APIs are used
19in a similar manner.
20
21To support using this npm package from both environments, the package uses "conditional exports"
22<https://nodejs.org/dist/latest-v18.x/docs/api/packages.html#conditional-exports> to expose one
23entry point for Node.js, and another for browsers. The distinct entry points uses their respective
24loader to load the wasm module for the platform, and then expose functionality that uses the
25loaded module via common code.
26
27When bundling for the web, bundlers such as esbuild will automatically use the default entry point,
28whereas when loaded as a Node.js module, it will use the "node" entry point.
29
30Note that TypeScript seems to add the ['import', 'types', 'node'] conditions by default when
31searching the Node.js `exports`, and so will always find the 'node' export before the 'default'
32export. To resolve this, a 'browser' condition was added (which is same as 'default' but earlier
33than 'node') and the tsconfig compiler option `"customConditions": ["browser"]` should be added
34(requires TypeScript 5.0 or later). esbuild also adds the 'browser' condition when bundling for
35the browser (see <https://esbuild.github.io/api/#how-conditions-work>).
36
37## Design
38
39The API for using this module is similar whether using a browser or Node.js, and whether running
40in the main thread or a worker thread. You instantiate the compiler, and call operations on it
41which complete in the order called.
42
43All operations return a Promise which resolves then the operation is complete. Some operations
44may also emit events, such as debug messages or state dumps as they are processed. A call may
45also be passed a CancellationToken so that if the result is no longer needed then the operation
46may be cancelled before starting.
47
48If the caller is not interested in any interim events or being able to cancel the request,
49these arguments are optional. For example:
50
51```js
52const codeSample = "namespace Test { operation Main() {....} }";
53const entryPoint = "Test.Main()";
54
55const compiler = getCompilerWorker();
56const cancelSrc = new CancellationTokenSource();
57const runEvents = new QscEventTarget(false /* store record of events */);
58
59// Log any DumpMachine calls
60runEvents.addEventListener('DumpMachine', (evt) => console.log("DumpMachine: %o", evt.detail));
61
62compiler.run(codeSample, entryPoint, 1 /* shots */, runEvents, cancelSrc.token)
63 .then(result => console.log("Run result: %s", result));
64 .catch(err => console.err("Run failed with: %o", err));
65
66cancelButton.addEventListener('click', () => {
67 // Try to cancel the operation if still pending
68 tokenSource.cancel();
69});
70
71// Also run the below request, but don't care about events or cancellation, just the result
72const checkResult = await compiler.check(code);
73console.log('check result was: %o', checkResult);
74```
75
76Promises, Events, and Cancellation are based on JavaScript or Web standards, or the VS Code API:
77
78- Promises <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises>
79- EventTarget <https://developer.mozilla.org/en-US/docs/Web/API/EventTarget>
80- Event <https://developer.mozilla.org/en-US/docs/Web/API/Event/Event>
81- VS Code API for CancellationToken <https://code.visualstudio.com/api/references/vscode-api#CancellationToken>
82
83The standard Web APIs for custom events were added to Node.js in v16.17. <https://nodejs.org/dist/v16.17.0/docs/api/events.html>, but behind an experimental flag. As CustomEvent is not on
84the global by default until v19 or later, the code will use Event with a 'detail'
85property manually set until v20 is in common use.
86
87The VS Code implementation for cancellation tokens is viewable in their source code
88at <src/vs/base/common/cancellation.ts>. This code uses a simplified version of that API.
89
90## Testing
91
92Node.js tests can be run via `node --test` (see
93<https://nodejs.org/dist/latest-v18.x/docs/api/test.html#test-runner-execution-model>).
94
95The test module was also added to Node.js v16.17.0, and Electron 22 (which VS Code plans to move to
96in first half of 2023) includes v16.17.1, so v16.17 should be our minimum Node.js
97version supported (it shipped in Aug 2022).
98