Share a secret across ES6 specific modules, so that other modules cannot access the secret?
Allen Wirfs-Brock
allen at wirfs-brock.com
Mon Apr 24 20:43:35 UTC 2017
> On Apr 24, 2017, at 12:34 PM, Bradley Meck <bradley.meck at gmail.com> wrote:
>
> To an extent, yes. You can use hoisting of function declarations and circular dependencies to create a "gateway". During circular dependencies, you have a time where function declarations are available but evaluation has not occured. During that time you can setup your private state. Then, immediately on evaluation, remove your gateway.
>
> ```
> // file: ./secrets
>
> // import all friendly modules (note: all dependencies of these modules could access GATEWAY)
> import './a'
> GATEWAY = void 0;
>
>
> // storage for shared secrets
> let SECRET;
Really clever!
Doesn’t this need to be a `var` declaration. Otherwise, the initial test of SECRET will be in its TDZ the first time GATEWAY is called.
> // gateway
> function GATEWAY() {
> if (!SECRET) SECRET = {};
> return SECRET;
> }
> export {GATEWAY};
> ```
>
> ```
> // file: ./a
> import {GATEWAY} from './secrets';
> if (typeof GATEWAY !== 'function') {
> throw Error('import secrets *first*.');
> }
> const SECRET = GATEWAY();
> ```
>
> With Realms (https://github.com/tc39/proposal-realms <https://github.com/tc39/proposal-realms>) you may be able to use the completion value of Module Evaluation to also achieve a way to share private state in a more sane way. VM implementations allow this in some ways as well : https://github.com/v8/v8/blob/a71c338d9e24e55b47125108a0fce754076751d0/include/v8.h#L1109 <https://github.com/v8/v8/blob/a71c338d9e24e55b47125108a0fce754076751d0/include/v8.h#L1109>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170424/ef6cc711/attachment-0001.html>
More information about the es-discuss
mailing list