context 1.1.4 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # context - Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
6
+
7
+ ## 1.2.1 - 2021-12-24
8
+ ### Fixed and improved
9
+ - 7e8d48d Update changelog (ealush)
10
+
11
+ ## 2.0.0 2021-12-24
12
+
13
+ - 7c43eab major(context): use named export in context (ealush)
14
+
15
+ ## 1.1.16 - 2021-07-02
16
+
17
+ ### Fixed and improved
18
+
19
+ - 34e0414 improved conditions (undefined)
20
+ - 33f4e46 release (undefined)
21
+ - 6fe40c7 better bundle (undefined)
22
+ - c6387ab before ts settings (undefined)
23
+ - c0e9708 generate correct d.ts file (undefined)
24
+ - 8e01b8e x (undefined)
25
+ - afb3960 x (undefined)
26
+ - e0a8463 add changelog support (undefined)
27
+ - cc46c38 current (undefined)
28
+
29
+ ## 1.1.15 - 2021-07-02
30
+
31
+ ### Fixed and improved
32
+
33
+ - 34e0414 improved conditions (undefined)
34
+ - 33f4e46 release (undefined)
35
+ - 6fe40c7 better bundle (undefined)
36
+ - c6387ab before ts settings (undefined)
37
+ - c0e9708 generate correct d.ts file (undefined)
38
+ - 8e01b8e x (undefined)
39
+ - afb3960 x (undefined)
40
+ - e0a8463 add changelog support (undefined)
41
+ - cc46c38 current (undefined)
package/README.md CHANGED
@@ -1,434 +1,140 @@
1
1
  # Context
2
2
 
3
- Simple utility that creates a multi-layered context singleton.
4
- It allows you to keep reference for shared variables, and access them later down in your function call even if not declared in the same scope.
3
+ Simple utility for context propagation within Javascript applications and libraries. Loosely based on the ideas behind React's context, allows you to achieve the same goals (and more) without actually using react.
4
+ It allows you to keep reference for shared variables, and access them down in your function call even if not declared in the same scope.
5
5
 
6
- Originally built for [vest](https://github.com/ealush/vest) validation framework.
6
+ ## How Context Works?
7
7
 
8
- # The Concepts
8
+ The way context works is quite simple. Creating a context initializes a closure with a context storage object. When you run your context call, it takes your values, and places them in the context storage object. When your function finishes running, the context is cleared.
9
9
 
10
- Lets take a quick look at how this would work
10
+ ![image](https://user-images.githubusercontent.com/11255103/137119151-6912d3f1-ab48-4c91-a426-76af8abc8c55.png)
11
11
 
12
- ```js
13
- import createContext from 'context';
14
-
15
- const context = createContext();
16
-
17
- context.run({ name: 'Sam' }, sayMyName);
18
- context.run({ name: 'David' }, sayMyName);
19
-
20
- function sayMyName() {
21
- const { name } = context.use();
22
- console.log(`My Name is ${name}`);
23
- }
24
- ```
12
+ The reason the context is cleared after its run is so that items can't override one another. Assume you have two running the same async function twice, and it writes to the context, expecting to read the value somewhere down the line. Now you have two competing consumers of this single resource, and one eventually get the wrong value since they both read from and write to the same place.
25
13
 
26
- This will print:
14
+ ## API Reference
27
15
 
28
- My Name is Sam
29
- My Name is David
16
+ Context tries to mimic the behavior of Javascript scopes without actually being in the same scopes, and the API is built around context initialization, setting of values within the context and retrieving values.
30
17
 
31
- So as we see 'run' allows us to run a function and access the specific variable we assigned to the object.
18
+ ### createContext()
32
19
 
33
- Why is this useful? Why not just do
20
+ Context's default export, it creates a context singleton object that can later be referenced.
34
21
 
35
22
  ```js
36
- sayMyName('Sam');
37
- sayMyName('David');
23
+ // ctx.js
24
+ import { createContext } from 'context';
38
25
 
39
- function sayMyName(name) {
40
- console.log(`My Name is ${name}`);
41
- }
26
+ export default createContext(); // { run: ƒ, bind: ƒ, use: ƒ, useX: ƒ }
42
27
  ```
43
28
 
44
- We will be getting the same results. Right?
45
-
46
- It's the next feature that illustrates context's power.
47
- Instead of using 'run'. we will use 'bind'
29
+ createContext also accepts an initialization function that's run every time ctx.run is called. It allows intercepting the context initialization and adding custom logic, or default values.
30
+ The init function is passed the context object run was called with, and the parent context if it was called within a previously created context. The init function needs to return the desired context object.
48
31
 
49
32
  ```js
50
- // getNames.js
51
-
52
- import createContext from 'context';
53
-
54
- const context = createContext();
55
-
56
- const samName = context.bind({ name: 'Sam' }, sayMyName);
57
- const davidName = context.bind({ name: 'David' }, sayMyName);
58
-
59
- function sayMyName() {
60
- const { name } = context.use();
61
- console.log(`My Name is ${name}`);
62
- }
63
-
64
- export { samName, davidName };
65
-
66
- //index.js
67
-
68
- samName();
69
- davidName();
70
- ```
71
-
72
- This will once again print
73
-
74
- My Name is Sam
75
- My Name is David
76
-
77
- Except now, because context is a singleton anywhere we run these functions they will print those values.
78
-
79
- What if we want to share a value between these functions?
80
- We can initialize createContext with a value
81
-
82
- ```js
83
- // getNames.js
84
-
85
- import createContext from 'context';
33
+ createContext((ctx, parentContext) => {
34
+ if (parentContext === null) {
35
+ // we're at the top level
36
+ // so let's add a default cart object
37
+ return Object.assign(ctx, {
38
+ cart: [],
39
+ });
40
+ }
86
41
 
87
- const context = createContext((ctx, parentCtx) => {
88
- return Object.assign({}, ctx, { lastName: 'Smith' });
42
+ // we're in a sub context, so we already have those default values.
43
+ return ctx;
89
44
  });
90
-
91
- const samName = context.bind({ name: 'Sam' }, sayMyName);
92
- const davidName = context.bind({ name: 'David' }, sayMyName);
93
-
94
- function sayMyName() {
95
- const { name, lastName } = context.use();
96
- console.log(`My Name is ${name} ${lastName}`);
97
- }
98
-
99
- export { samName, davidName };
100
-
101
- //index.js
102
-
103
- samName();
104
- davidName();
105
- ```
106
-
107
- will print
108
-
109
- My Name is Sam Smith
110
- My Name is David Smith
111
-
112
- These example are pretty contrived
113
-
114
- Lets try something a little more real world.
115
-
116
- # Real World Example
117
-
118
- What if we wanted to keep track of how many times a function was called.
119
- We want to create an environment where we pass the function we want to track and receive exactly the same function.
120
- The only difference is that the function is going to have a count property which we will be able to call at any time.
121
-
122
- So lets start
123
-
124
- ```js
125
- //counter.js
126
- import createContext from 'context';
127
-
128
- const context = createContext();
129
45
  ```
130
46
 
131
- We've seen this before, we are creating the context object.
47
+ ### run()
132
48
 
133
- Now I want to have a main context that will store the values of all the functions that are running.
134
- in context world it will look like this.
135
- Just a parent function called counter.
49
+ Runs a callback function within the context. It takes an object referencing the data you want to store within your context, and a callback function to run.
136
50
 
137
51
  ```js
138
- //counter.js
139
- import createContext from 'context';
140
-
141
- const context = createContext();
142
-
143
- function counter() {}
144
- ```
145
-
146
- In this function I am going to want to store the function name and the count.
147
- I add a couple of functions add and getVals.
52
+ // myFunction.js
53
+ import ctx from './ctx';
54
+ import sayUsername from './sayUsername';
148
55
 
149
- ```js
150
- //counter.js
151
- import createContext from 'context';
152
-
153
- const context = createContext();
154
-
155
- function counter() {
156
- const values = {};
157
-
158
- function add(val) {
159
- if (!values[val]) {
160
- values[val] = 0;
161
- }
162
-
163
- values[val] += 1;
164
- }
165
-
166
- function getVals() {
167
- return values;
168
- }
56
+ function myFunction(username) {
57
+ return ctx.run({ username }, sayUsername);
169
58
  }
170
59
  ```
171
60
 
172
- At this stage it won't accomplish much.
173
- What I want counter to return is a function that holds 'values' in its context. We will use context.bind for that.
174
- So imagine a box and counter is the outer most box. In it is the values object and anything I put into the box will have access to that object.
175
- and what do I want to put in the box? The function I want to count.
61
+ If `run` is called within a different `run` call, the context values will be merged when the callback is run. When we exit our callback, the context will be reset to the values it had before the call.
176
62
 
177
- I add an argument func to counter.
178
- This will be the function we want to count.
179
- I create a ref object which I will then pass to the function.
180
- This object is accessible to the the function thanks to context.
63
+ ### use() and useX()
181
64
 
182
- ```js
183
- //counter.js
184
- import createContext from 'context';
185
-
186
- const context = createContext();
187
-
188
- function counter(func) {
189
- const values = {};
190
-
191
- function add(val) {
192
- if (!values[val]) {
193
- values[val] = 0;
194
- }
65
+ These are the main ways to access the context within your code. They return the current object that stored within the context, and differ in the way they handle calls outside of the context.
195
66
 
196
- values[val] += 1;
197
- }
198
-
199
- function getVals() {
200
- return values;
201
- }
202
-
203
- const ref = { add, getVals };
204
- return context.bind({ ref }, func);
205
- }
206
- ```
207
-
208
- great! wait no, this function that is returned will run our function we passed and it does have access to values but in order to use values we have to modify our function!
209
-
210
- Not what we wanted...
211
-
212
- We want a function that will run our function, have access to values but won't require us to modify our existing function.
213
-
214
- so lets create a function called track.
215
- 'track' will return a function that will modify values and run out function
216
-
217
- ```js
218
- //counter.js
219
- function track(func) {
220
-   const { ref } = context.use();
221
-
222
-  
223
-   function holder(args) {
224
-     ref.add(func.name);
225
-     holder.count = ref.getVals()[func.name];
226
-     holder.getAll = () => {
227
-       return ref.getVals();
228
-     };
229
-     return func(args);
230
-   }
231
-
232
-   return holder;
233
- }
234
-  
235
-
236
-
237
- ```
238
-
239
- In 'track' I am using context.use and I can do this because I am going to pass it to context.bind. If I didn't run it in either context.run or context.bind this will not work. It basically is looking for the outer box.
240
-
241
- I pull out ref which holds the reference to values.
242
-
243
- The function 'holder' is going to run 'add' from ref and since functions in javascript are object we are going to pass the resulting value into a 'count' property.
244
- We are also creating a getAll function to the function.
245
- Then our function will run and the result will return as if no change was ever made.
67
+ - use() returns the current object stored within the context, or null if we're not within a `run` call.
68
+ - useX() returns the current object stored within the context, or throws an error if we're not within a `run` call.
69
+ - useX also takes an optional argument that will be used as the error message if the context is not found.
246
70
 
247
71
  ```js
248
- //counter.js
249
- import createContext from 'context';
72
+ // sayUsername.js
73
+ import ctx from './ctx';
250
74
 
251
- const context = createContext();
75
+ function sayUsername() {
76
+ const context = ctx.use(); // { username: 'John Doe' }
252
77
 
253
- function track(func) {
254
- const { ref } = context.use();
255
-
256
- function holder(args) {
257
- ref.add(func.name);
258
- holder.count = ref.getVals()[func.name];
259
- holder.getAll = () => {
260
- return ref.getVals();
261
- };
262
- return func(args);
78
+ if (!context) {
79
+ // we're not within a `run` call. This function was called outside of a running context.
80
+ return "Hey, I don't know you, and this is crazy!";
263
81
  }
264
82
 
265
- return holder;
83
+ return `Hello, ${context.username}!`;
266
84
  }
267
-
268
- function counter(tracker) {
269
- const values = {};
270
-
271
- function add(val) {
272
- if (!values[val]) {
273
- values[val] = 0;
274
- }
275
-
276
- values[val] += 1;
277
- }
278
-
279
- function getVals() {
280
- return values;
281
- }
282
-
283
- const ref = { add, getVals };
284
-
285
- return context.bind({ ref }, tracker); //
286
- }
287
-
288
- export { counter, track };
289
85
  ```
290
86
 
291
- Lets see how we use this.
292
-
293
87
  ```js
294
- // index.js
295
- import { counter, track } from './counter';
88
+ // handleCart.js
89
+ import ctx from './ctx';
296
90
 
297
- const countIt = counter(func => {
298
- return track(func);
299
- });
300
-
301
- function goToServer() {
302
- console.log('going to server');
303
- }
91
+ function handleCart() {
92
+ const context = ctx.useX(
93
+ 'handleCart was called outside of a running context'
94
+ ); // { cart: { items: [ 'foo', 'bar' ] } }
95
+ // This throws an error if we're not within a `run` call.
96
+ // You should catch this error and handle it somewhere above this function.
304
97
 
305
- function readFile(file) {
306
- console.log('readingFile ' + file);
98
+ return `You have ${context.cart.items.length} items in your cart.`;
307
99
  }
308
- const dReadFile = countIt(readFile);
309
- const dgoToServer = countIt(goToServer);
310
-
311
- readFile('important.docx');
312
-
313
- dReadFile('mainfile.js');
314
- dReadFile('secondary.js');
315
- console.log(dReadFile.count);
316
-
317
- dgoToServer();
318
- console.log(dgoToServer.count);
319
-
320
- console.log(dReadFile.getAll());
321
100
  ```
322
101
 
323
- Imagine a situation where you have functions that are trying to reach a server and read a file.
324
-
325
- We don't want to modify them but create a wrapper function to keep track
326
- of how many times it runs.
327
-
328
- So to create our first box we have the counter function.
329
- It stores the values and receives a deferred anonymous function.
330
- We are passing our function the anonymous function which then gets passed to the tracker function.
331
- The tracker function receives our function runs the count returns the result of our function
332
-
333
- We assign this wrapper to the variable countIt.
334
-
335
- We pass readFile to countIt and create a new function dReadFile
102
+ ### bind()
336
103
 
337
- When we run dReadFile it will behave like readFile but will store the count within.
338
-
339
- Since context is a singleton anywhere we run this function within our project it will keep correct track of our count.
340
-
341
- # Other Examples
104
+ Bind a function to a context. It takes an object referencing the data you want to store within your context, and a callback function to run. It returns a function that can be called with the same arguments as the original function. The function will then internally call `run` with the same arguments, and return the result of the callback function, so it is useful if you want to reference a context after it was closed, for example - when running an async function.
342
105
 
343
106
  ```js
344
- // myContext.js
345
- import createContext from 'context';
346
-
347
- export default createContext();
348
- ```
349
-
350
- ```js
351
- // framework.js
352
-
353
- import context from './myContext.js';
107
+ // getProductData.js
108
+ import ctx from './ctx';
354
109
 
355
- function suite(id, tests) {
356
- context.run({ suiteId: id }, () => tests()); // ...
357
- }
358
-
359
- function group(name, groupTests) {
360
- const { suiteId } = context.use();
110
+ function getProductData(productId) {
111
+ return ctx.bind({ productId }, handleProductData);
361
112
 
362
- context.run(
363
- {
364
- group: name,
365
- },
366
- () => groupTests()
367
- );
113
+ fetchProduct(productId).then(data => {
114
+ handleProductData(data);
115
+ // will run the function handleProductData within our context, even though there is no context running at the moment.
116
+ });
368
117
  }
118
+ ```
369
119
 
370
- function test(message, cb) {
371
- const { suiteId, group } = context.use();
120
+ ## Troubleshooting
372
121
 
373
- const testId = Math.random(); // 0.8418151199238901
122
+ ### Working with async functions/promises
374
123
 
375
- const testData = context.run({ test: testId }, () => cb()); // ...
376
- }
124
+ Working with context inside within async code may lead to unexpected results when we don't fully consider what's happening. Trying to call your context from the async part of your code will probably return `null` instead of your values.
377
125
 
378
- export { suite, group, test } from './framework';
379
- ```
126
+ This is known and expected behavior. Context is a synchronous context propagation tool that completely relies on the synchronous nature of function calls in JS - this is exactly what allows context to run.
380
127
 
381
- ```js
382
- import testFramework from './framwork.js';
383
-
384
- suite('some_id', () => {
385
- /*
386
-     context now is:
387
-     {
388
-       suiteId: 'some_id'
389
-     }
390
-  */
391
-
392
- group('some_group_name', () => {
393
- /*
394
-       context now is:
395
-       {
396
-         group: 'some_group_name',
397
-         parentContext: {
398
-           suiteId: 'some_id',
399
-         }
400
-       }
401
-      */
402
-
403
- test('blah blah', () => {
404
- /*
405
-           context now is:
406
-           {
407
-             test: 0.8418151199238901,
408
-             parentContext: {
409
-               group: 'some_group_name',
410
-               parentContext: {
411
-                 suiteId: 'some_id',
412
-               }
413
-             }
414
-           }
415
-          */
416
- });
417
- });
418
- });
419
- ```
420
-
421
- ## Binding a function with context
128
+ #### But my function is still running. Why did the context clear?
422
129
 
423
- You can bind a function to a context with ctx.bind, this allows you to create a bound function that's when called - will be called with that bound context, even if not in the same scope anymore.
130
+ The async parts of your function are actually not executed along with your sync code, and even though you "await" it, the browser carries on and allows other code to run in between instead of blocking execution until your async code is complete.
424
131
 
425
- ```js
426
- const boundFunction = ctx.bind(ctxRef, fn, ...args);
427
-
428
- boundFunction(); // Will run with the context as if you run it directly within ctx.run();
429
- ```
132
+ #### Ok, so what do I do?
430
133
 
431
- ## Context initialization
134
+ There are multiple strategies of handling async functions with context.
432
135
 
433
- You can add an init function to your context creation. The init function will run every time you call context.run, to allow you to set in-flight keys to your context. It accepts two params - the provided ctxRef, and the parent context when nested.
136
+ 1. Pulling your values from context right before your async call
137
+ This is the most obvious and easiest to achieve, though not always what you need. The basic idea is that you take whatever you need from the context when it is still available to you.
434
138
 
139
+ 2. context.bind or context.run your async function to the context you extracted
140
+ This is the next logical step - you have a function that you know should run later with your context. You can bind your context to it for delayed execution. When your function runs later down the line within your asynchronous code, internally it will still have access to whatever you bound to it.
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var assign = Object.assign;
6
+
7
+ function isFunction(value) {
8
+ return typeof value === 'function';
9
+ }
10
+
11
+ function optionalFunctionValue(value) {
12
+ var args = [];
13
+ for (var _i = 1; _i < arguments.length; _i++) {
14
+ args[_i - 1] = arguments[_i];
15
+ }
16
+ return isFunction(value) ? value.apply(void 0, args) : value;
17
+ }
18
+
19
+ function defaultTo(callback, defaultValue) {
20
+ var _a;
21
+ return (_a = optionalFunctionValue(callback)) !== null && _a !== void 0 ? _a : defaultValue;
22
+ }
23
+
24
+ /**
25
+ * Throws a timed out error.
26
+ */
27
+ function throwError(devMessage, productionMessage) {
28
+ throw new Error(devMessage );
29
+ }
30
+
31
+ // eslint-disable-next-line max-lines-per-function
32
+ function createContext(init) {
33
+ var storage = { ancestry: [] };
34
+ return {
35
+ bind: bind,
36
+ run: run,
37
+ use: use,
38
+ useX: useX
39
+ };
40
+ function useX(errorMessage) {
41
+ var _a;
42
+ return ((_a = storage.ctx) !== null && _a !== void 0 ? _a : throwError(defaultTo(errorMessage, 'Context was used after it was closed')));
43
+ }
44
+ function run(ctxRef, fn) {
45
+ var _a;
46
+ var parentContext = use();
47
+ var out = assign({}, parentContext ? parentContext : {}, (_a = optionalFunctionValue(init, ctxRef, parentContext)) !== null && _a !== void 0 ? _a : ctxRef);
48
+ var ctx = set(Object.freeze(out));
49
+ storage.ancestry.unshift(ctx);
50
+ var res = fn(ctx);
51
+ clear();
52
+ return res;
53
+ }
54
+ function bind(ctxRef, fn) {
55
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
56
+ // @ts-ignore - this one's pretty hard to get right
57
+ var returnedFn = function () {
58
+ var runTimeArgs = [];
59
+ for (var _i = 0; _i < arguments.length; _i++) {
60
+ runTimeArgs[_i] = arguments[_i];
61
+ }
62
+ return run(ctxRef, function () {
63
+ return fn.apply(void 0, runTimeArgs);
64
+ });
65
+ };
66
+ return returnedFn;
67
+ }
68
+ function use() {
69
+ return storage.ctx;
70
+ }
71
+ function set(value) {
72
+ return (storage.ctx = value);
73
+ }
74
+ function clear() {
75
+ var _a;
76
+ storage.ancestry.shift();
77
+ set((_a = storage.ancestry[0]) !== null && _a !== void 0 ? _a : null);
78
+ }
79
+ }
80
+
81
+ exports.createContext = createContext;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var n=Object.assign;function t(n){return"function"==typeof n}function r(n){for(var r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];return t(n)?n.apply(void 0,r):n}function e(n,t){var e;return null!==(e=r(n))&&void 0!==e?e:t}exports.createContext=function(t){function u(e,u){var i,f,a=o();return e=n({},a||{},null!==(i=r(t,e,a))&&void 0!==i?i:e),i=c.ctx=Object.freeze(e),c.ancestry.unshift(i),u=u(i),c.ancestry.shift(),c.ctx=null!==(f=c.ancestry[0])&&void 0!==f?f:null,u}function o(){return c.ctx}var c={ancestry:[]};return{bind:function(n,t){return function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return u(n,(function(){return t.apply(void 0,r)}))}},run:u,use:o,useX:function(n){var t;return null!==(t=c.ctx)&&void 0!==t?t:function(n,t){throw Error(e(t,n))}(e(n,"Context was used after it was closed"))}}};
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,77 @@
1
+ var assign = Object.assign;
2
+
3
+ function isFunction(value) {
4
+ return typeof value === 'function';
5
+ }
6
+
7
+ function optionalFunctionValue(value) {
8
+ var args = [];
9
+ for (var _i = 1; _i < arguments.length; _i++) {
10
+ args[_i - 1] = arguments[_i];
11
+ }
12
+ return isFunction(value) ? value.apply(void 0, args) : value;
13
+ }
14
+
15
+ function defaultTo(callback, defaultValue) {
16
+ var _a;
17
+ return (_a = optionalFunctionValue(callback)) !== null && _a !== void 0 ? _a : defaultValue;
18
+ }
19
+
20
+ /**
21
+ * Throws a timed out error.
22
+ */
23
+ function throwError(devMessage, productionMessage) {
24
+ throw new Error(devMessage );
25
+ }
26
+
27
+ // eslint-disable-next-line max-lines-per-function
28
+ function createContext(init) {
29
+ var storage = { ancestry: [] };
30
+ return {
31
+ bind: bind,
32
+ run: run,
33
+ use: use,
34
+ useX: useX
35
+ };
36
+ function useX(errorMessage) {
37
+ var _a;
38
+ return ((_a = storage.ctx) !== null && _a !== void 0 ? _a : throwError(defaultTo(errorMessage, 'Context was used after it was closed')));
39
+ }
40
+ function run(ctxRef, fn) {
41
+ var _a;
42
+ var parentContext = use();
43
+ var out = assign({}, parentContext ? parentContext : {}, (_a = optionalFunctionValue(init, ctxRef, parentContext)) !== null && _a !== void 0 ? _a : ctxRef);
44
+ var ctx = set(Object.freeze(out));
45
+ storage.ancestry.unshift(ctx);
46
+ var res = fn(ctx);
47
+ clear();
48
+ return res;
49
+ }
50
+ function bind(ctxRef, fn) {
51
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
52
+ // @ts-ignore - this one's pretty hard to get right
53
+ var returnedFn = function () {
54
+ var runTimeArgs = [];
55
+ for (var _i = 0; _i < arguments.length; _i++) {
56
+ runTimeArgs[_i] = arguments[_i];
57
+ }
58
+ return run(ctxRef, function () {
59
+ return fn.apply(void 0, runTimeArgs);
60
+ });
61
+ };
62
+ return returnedFn;
63
+ }
64
+ function use() {
65
+ return storage.ctx;
66
+ }
67
+ function set(value) {
68
+ return (storage.ctx = value);
69
+ }
70
+ function clear() {
71
+ var _a;
72
+ storage.ancestry.shift();
73
+ set((_a = storage.ancestry[0]) !== null && _a !== void 0 ? _a : null);
74
+ }
75
+ }
76
+
77
+ export { createContext };
@@ -0,0 +1 @@
1
+ var n=Object.assign;function t(n){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return"function"==typeof n?n.apply(void 0,t):n}function r(n,r){var e;return null!==(e=t(n))&&void 0!==e?e:r}export function createContext(e){function u(r,u){var c,a,f=o();return r=n({},f||{},null!==(c=t(e,r,f))&&void 0!==c?c:r),c=i.ctx=Object.freeze(r),i.ancestry.unshift(c),u=u(c),i.ancestry.shift(),i.ctx=null!==(a=i.ancestry[0])&&void 0!==a?a:null,u}function o(){return i.ctx}var i={ancestry:[]};return{bind:function(n,t){return function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return u(n,(function(){return t.apply(void 0,r)}))}},run:u,use:o,useX:function(n){var t;if(null===(t=i.ctx)||void 0===t)throw n=r(n,"Context was used after it was closed"),Error(r(void 0,n));return t}}}
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,87 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.context = {}));
5
+ }(this, (function (exports) { 'use strict';
6
+
7
+ var assign = Object.assign;
8
+
9
+ function isFunction(value) {
10
+ return typeof value === 'function';
11
+ }
12
+
13
+ function optionalFunctionValue(value) {
14
+ var args = [];
15
+ for (var _i = 1; _i < arguments.length; _i++) {
16
+ args[_i - 1] = arguments[_i];
17
+ }
18
+ return isFunction(value) ? value.apply(void 0, args) : value;
19
+ }
20
+
21
+ function defaultTo(callback, defaultValue) {
22
+ var _a;
23
+ return (_a = optionalFunctionValue(callback)) !== null && _a !== void 0 ? _a : defaultValue;
24
+ }
25
+
26
+ /**
27
+ * Throws a timed out error.
28
+ */
29
+ function throwError(devMessage, productionMessage) {
30
+ throw new Error(devMessage );
31
+ }
32
+
33
+ // eslint-disable-next-line max-lines-per-function
34
+ function createContext(init) {
35
+ var storage = { ancestry: [] };
36
+ return {
37
+ bind: bind,
38
+ run: run,
39
+ use: use,
40
+ useX: useX
41
+ };
42
+ function useX(errorMessage) {
43
+ var _a;
44
+ return ((_a = storage.ctx) !== null && _a !== void 0 ? _a : throwError(defaultTo(errorMessage, 'Context was used after it was closed')));
45
+ }
46
+ function run(ctxRef, fn) {
47
+ var _a;
48
+ var parentContext = use();
49
+ var out = assign({}, parentContext ? parentContext : {}, (_a = optionalFunctionValue(init, ctxRef, parentContext)) !== null && _a !== void 0 ? _a : ctxRef);
50
+ var ctx = set(Object.freeze(out));
51
+ storage.ancestry.unshift(ctx);
52
+ var res = fn(ctx);
53
+ clear();
54
+ return res;
55
+ }
56
+ function bind(ctxRef, fn) {
57
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
58
+ // @ts-ignore - this one's pretty hard to get right
59
+ var returnedFn = function () {
60
+ var runTimeArgs = [];
61
+ for (var _i = 0; _i < arguments.length; _i++) {
62
+ runTimeArgs[_i] = arguments[_i];
63
+ }
64
+ return run(ctxRef, function () {
65
+ return fn.apply(void 0, runTimeArgs);
66
+ });
67
+ };
68
+ return returnedFn;
69
+ }
70
+ function use() {
71
+ return storage.ctx;
72
+ }
73
+ function set(value) {
74
+ return (storage.ctx = value);
75
+ }
76
+ function clear() {
77
+ var _a;
78
+ storage.ancestry.shift();
79
+ set((_a = storage.ancestry[0]) !== null && _a !== void 0 ? _a : null);
80
+ }
81
+ }
82
+
83
+ exports.createContext = createContext;
84
+
85
+ Object.defineProperty(exports, '__esModule', { value: true });
86
+
87
+ })));
@@ -0,0 +1 @@
1
+ "use strict";!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((n="undefined"!=typeof globalThis?globalThis:n||self).context={})}(this,(function(n){function t(n){for(var t=[],e=1;e<arguments.length;e++)t[e-1]=arguments[e];return"function"==typeof n?n.apply(void 0,t):n}function e(n,e){var r;return null!==(r=t(n))&&void 0!==r?r:e}var r=Object.assign;n.createContext=function(n){function o(e,o){var f,c,s=u();return e=r({},s||{},null!==(f=t(n,e,s))&&void 0!==f?f:e),f=i.ctx=Object.freeze(e),i.ancestry.unshift(f),o=o(f),i.ancestry.shift(),i.ctx=null!==(c=i.ancestry[0])&&void 0!==c?c:null,o}function u(){return i.ctx}var i={ancestry:[]};return{bind:function(n,t){return function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return o(n,(function(){return t.apply(void 0,e)}))}},run:o,use:u,useX:function(n){var t;if(null===(t=i.ctx)||void 0===t)throw n=e(n,"Context was used after it was closed"),Error(e(void 0,n));return t}}},Object.defineProperty(n,"__esModule",{value:!0})}));
package/package.json CHANGED
@@ -1,45 +1,46 @@
1
1
  {
2
- "version": "1.1.4",
2
+ "version": "1.2.1",
3
3
  "license": "MIT",
4
- "main": "dist/index.js",
5
- "typings": "dist/index.d.ts",
6
- "files": [
7
- "dist",
8
- "src"
9
- ],
10
- "engines": {
11
- "node": ">=10"
12
- },
13
- "scripts": {
14
- "start": "tsdx watch",
15
- "build": "tsdx build",
16
- "test": "tsdx test",
17
- "lint": "tsdx lint",
18
- "prepare": "tsdx build"
19
- },
20
- "peerDependencies": {},
21
- "husky": {
22
- "hooks": {
23
- "pre-commit": "tsdx lint"
24
- }
25
- },
26
- "prettier": {
27
- "printWidth": 80,
28
- "semi": true,
29
- "singleQuote": true,
30
- "trailingComma": "es5"
31
- },
4
+ "main": "./dist/cjs/context.js",
5
+ "types": "./types/context.d.ts",
32
6
  "name": "context",
33
7
  "author": "ealush",
34
- "module": "dist/context.esm.js",
35
- "devDependencies": {
36
- "husky": "^4.2.5",
37
- "tsdx": "^0.13.2",
38
- "tslib": "^2.0.1",
39
- "typescript": "^4.0.2"
8
+ "scripts": {
9
+ "test": "vx test",
10
+ "build": "vx build",
11
+ "release": "vx release"
12
+ },
13
+ "module": "./dist/es/context.production.js",
14
+ "exports": {
15
+ ".": {
16
+ "development": {
17
+ "types": "./types/context.d.ts",
18
+ "browser": "./dist/es/context.development.js",
19
+ "umd": "./dist/umd/context.development.js",
20
+ "import": "./dist/es/context.development.js",
21
+ "require": "./dist/cjs/context.development.js",
22
+ "node": "./dist/cjs/context.development.js",
23
+ "module": "./dist/es/context.development.js",
24
+ "default": "./dist/cjs/context.development.js"
25
+ },
26
+ "types": "./types/context.d.ts",
27
+ "browser": "./dist/es/context.production.js",
28
+ "umd": "./dist/umd/context.production.js",
29
+ "import": "./dist/es/context.production.js",
30
+ "require": "./dist/cjs/context.production.js",
31
+ "node": "./dist/cjs/context.production.js",
32
+ "module": "./dist/es/context.production.js",
33
+ "default": "./dist/cjs/context.production.js"
34
+ },
35
+ "./package.json": "./package.json",
36
+ "./": "./"
40
37
  },
41
38
  "repository": {
42
39
  "type": "git",
43
- "url": "git+https://github.com/ealush/context.git"
40
+ "url": "https://github.com/ealush/vest.git",
41
+ "directory": "packages/context"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/ealush/vest.git/issues"
44
45
  }
45
46
  }
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "declarationMap": true,
5
+ "declarationDir": "./types",
6
+ "outDir": "./dist"
7
+ }
8
+ }
@@ -0,0 +1,7 @@
1
+ declare function createContext<T extends Record<string, unknown>>(init?: (ctxRef: Partial<T>, parentContext: T | void) => T | null): {
2
+ run: <R>(ctxRef: Partial<T>, fn: (context: T) => R) => R;
3
+ bind: <Fn extends (...args: any[]) => any>(ctxRef: Partial<T>, fn: Fn) => Fn;
4
+ use: () => T | undefined;
5
+ useX: (errorMessage?: string) => T;
6
+ };
7
+ export { createContext };
@@ -1,80 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _extends() {
6
- _extends = Object.assign || function (target) {
7
- for (var i = 1; i < arguments.length; i++) {
8
- var source = arguments[i];
9
-
10
- for (var key in source) {
11
- if (Object.prototype.hasOwnProperty.call(source, key)) {
12
- target[key] = source[key];
13
- }
14
- }
15
- }
16
-
17
- return target;
18
- };
19
-
20
- return _extends.apply(this, arguments);
21
- }
22
-
23
- function createContext(init) {
24
- var storage = {
25
- ancestry: []
26
- };
27
- return {
28
- run: run,
29
- bind: bind,
30
- use: use
31
- };
32
-
33
- function run(ctxRef, fn) {
34
- var _init;
35
-
36
- var parentContext = use();
37
-
38
- var out = _extends({}, parentContext ? parentContext : {}, (_init = init === null || init === void 0 ? void 0 : init(ctxRef, parentContext)) !== null && _init !== void 0 ? _init : ctxRef);
39
-
40
- var ctx = set(Object.freeze(out));
41
- storage.ancestry.unshift(ctx);
42
- var res = fn(ctx);
43
- clear();
44
- return res;
45
- }
46
-
47
- function bind(ctxRef, fn) {
48
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
49
- args[_key - 2] = arguments[_key];
50
- }
51
-
52
- return function () {
53
- for (var _len2 = arguments.length, runTimeArgs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
54
- runTimeArgs[_key2] = arguments[_key2];
55
- }
56
-
57
- return run(ctxRef, function () {
58
- return fn.apply(void 0, args.concat(runTimeArgs));
59
- });
60
- };
61
- }
62
-
63
- function use() {
64
- return storage.ctx;
65
- }
66
-
67
- function set(value) {
68
- return storage.ctx = value;
69
- }
70
-
71
- function clear() {
72
- var _storage$ancestry$;
73
-
74
- storage.ancestry.shift();
75
- set((_storage$ancestry$ = storage.ancestry[0]) !== null && _storage$ancestry$ !== void 0 ? _storage$ancestry$ : null);
76
- }
77
- }
78
-
79
- exports.default = createContext;
80
- //# sourceMappingURL=context.cjs.development.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context.cjs.development.js","sources":["../src/index.ts"],"sourcesContent":["export default function createContext<T extends Record<string, any>>(\n init?: (ctxRef: T, parentContext: T | void) => T | null\n) {\n const storage: { ctx?: T; ancestry: T[] } = { ancestry: [] };\n\n return {\n run,\n bind,\n use,\n };\n\n function run<R>(ctxRef: T, fn: (context: T) => R): R {\n const parentContext = use();\n\n const out = {\n ...(parentContext ? parentContext : {}),\n ...(init?.(ctxRef, parentContext) ?? ctxRef),\n };\n\n const ctx = set(Object.freeze(out));\n storage.ancestry.unshift(ctx);\n const res = fn(ctx);\n\n clear();\n return res;\n }\n\n function bind<R>(ctxRef: T, fn: (...args: any[]) => R, ...args: any[]) {\n return function(...runTimeArgs: any[]) {\n return run<R>(ctxRef, function() {\n return fn(...args, ...runTimeArgs);\n });\n };\n }\n\n function use() {\n return storage.ctx;\n }\n\n function set(value: T): T {\n return (storage.ctx = value);\n }\n\n function clear() {\n storage.ancestry.shift();\n set(storage.ancestry[0] ?? null);\n }\n}\n"],"names":["createContext","init","storage","ancestry","run","bind","use","ctxRef","fn","parentContext","out","ctx","set","Object","freeze","unshift","res","clear","args","runTimeArgs","value","shift"],"mappings":";;;;;;;;;;;;;;;;;;;;;;SAAwBA,cACtBC;AAEA,MAAMC,OAAO,GAA+B;AAAEC,IAAAA,QAAQ,EAAE;AAAZ,GAA5C;AAEA,SAAO;AACLC,IAAAA,GAAG,EAAHA,GADK;AAELC,IAAAA,IAAI,EAAJA,IAFK;AAGLC,IAAAA,GAAG,EAAHA;AAHK,GAAP;;AAMA,WAASF,GAAT,CAAgBG,MAAhB,EAA2BC,EAA3B;;;AACE,QAAMC,aAAa,GAAGH,GAAG,EAAzB;;AAEA,QAAMI,GAAG,gBACHD,aAAa,GAAGA,aAAH,GAAmB,EAD7B,WAEHR,IAFG,aAEHA,IAFG,uBAEHA,IAAI,CAAGM,MAAH,EAAWE,aAAX,CAFD,yCAE8BF,MAF9B,CAAT;;AAKA,QAAMI,GAAG,GAAGC,GAAG,CAACC,MAAM,CAACC,MAAP,CAAcJ,GAAd,CAAD,CAAf;AACAR,IAAAA,OAAO,CAACC,QAAR,CAAiBY,OAAjB,CAAyBJ,GAAzB;AACA,QAAMK,GAAG,GAAGR,EAAE,CAACG,GAAD,CAAd;AAEAM,IAAAA,KAAK;AACL,WAAOD,GAAP;AACD;;AAED,WAASX,IAAT,CAAiBE,MAAjB,EAA4BC,EAA5B;sCAA0DU;AAAAA,MAAAA;;;AACxD,WAAO;yCAAYC;AAAAA,QAAAA;;;AACjB,aAAOf,GAAG,CAAIG,MAAJ,EAAY;AACpB,eAAOC,EAAE,MAAF,SAAMU,IAAN,QAAeC,WAAf,EAAP;AACD,OAFS,CAAV;AAGD,KAJD;AAKD;;AAED,WAASb,GAAT;AACE,WAAOJ,OAAO,CAACS,GAAf;AACD;;AAED,WAASC,GAAT,CAAaQ,KAAb;AACE,WAAQlB,OAAO,CAACS,GAAR,GAAcS,KAAtB;AACD;;AAED,WAASH,KAAT;;;AACEf,IAAAA,OAAO,CAACC,QAAR,CAAiBkB,KAAjB;AACAT,IAAAA,GAAG,uBAACV,OAAO,CAACC,QAAR,CAAiB,CAAjB,CAAD,mEAAwB,IAAxB,CAAH;AACD;AACF;;;;"}
@@ -1,2 +0,0 @@
1
- "use strict";function n(){return(n=Object.assign||function(n){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n}).apply(this,arguments)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(r){var t={ancestry:[]};return{run:e,bind:function(n,r){for(var t=arguments.length,u=new Array(t>2?t-2:0),o=2;o<t;o++)u[o-2]=arguments[o];return function(){for(var t=arguments.length,o=new Array(t),c=0;c<t;c++)o[c]=arguments[c];return e(n,(function(){return r.apply(void 0,u.concat(o))}))}},use:u};function e(e,c){var a,i=u(),f=n({},i||{},null!==(a=null==r?void 0:r(e,i))&&void 0!==a?a:e),l=o(Object.freeze(f));t.ancestry.unshift(l);var s,v=c(l);return t.ancestry.shift(),o(null!==(s=t.ancestry[0])&&void 0!==s?s:null),v}function u(){return t.ctx}function o(n){return t.ctx=n}};
2
- //# sourceMappingURL=context.cjs.production.min.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context.cjs.production.min.js","sources":["../src/index.ts"],"sourcesContent":["export default function createContext<T extends Record<string, any>>(\n init?: (ctxRef: T, parentContext: T | void) => T | null\n) {\n const storage: { ctx?: T; ancestry: T[] } = { ancestry: [] };\n\n return {\n run,\n bind,\n use,\n };\n\n function run<R>(ctxRef: T, fn: (context: T) => R): R {\n const parentContext = use();\n\n const out = {\n ...(parentContext ? parentContext : {}),\n ...(init?.(ctxRef, parentContext) ?? ctxRef),\n };\n\n const ctx = set(Object.freeze(out));\n storage.ancestry.unshift(ctx);\n const res = fn(ctx);\n\n clear();\n return res;\n }\n\n function bind<R>(ctxRef: T, fn: (...args: any[]) => R, ...args: any[]) {\n return function(...runTimeArgs: any[]) {\n return run<R>(ctxRef, function() {\n return fn(...args, ...runTimeArgs);\n });\n };\n }\n\n function use() {\n return storage.ctx;\n }\n\n function set(value: T): T {\n return (storage.ctx = value);\n }\n\n function clear() {\n storage.ancestry.shift();\n set(storage.ancestry[0] ?? null);\n }\n}\n"],"names":["init","storage","ancestry","run","bind","ctxRef","fn","args","runTimeArgs","use","parentContext","out","ctx","set","Object","freeze","unshift","res","shift","value"],"mappings":"4SACEA,OAEMC,EAAsC,CAAEC,SAAU,UAEjD,CACLC,IAAAA,EACAC,cAoBeC,EAAWC,8BAA8BC,mCAAAA,2BACjD,sCAAYC,2BAAAA,yBACVL,EAAOE,GAAQ,kBACbC,eAAMC,SAASC,SAtB1BC,IAAAA,YAGON,EAAOE,EAAWC,SACnBI,EAAgBD,IAEhBE,OACAD,GAAgC,aAChCV,MAAAA,SAAAA,EAAOK,EAAQK,kBAAkBL,GAGjCO,EAAMC,EAAIC,OAAOC,OAAOJ,IAC9BV,EAAQC,SAASc,QAAQJ,SACnBK,EAAMX,EAAGM,UAuBfX,EAAQC,SAASgB,QACjBL,YAAIZ,EAAQC,SAAS,kBAAM,MArBpBe,WAWAR,WACAR,EAAQW,aAGRC,EAAIM,UACHlB,EAAQW,IAAMO"}
@@ -1,76 +0,0 @@
1
- function _extends() {
2
- _extends = Object.assign || function (target) {
3
- for (var i = 1; i < arguments.length; i++) {
4
- var source = arguments[i];
5
-
6
- for (var key in source) {
7
- if (Object.prototype.hasOwnProperty.call(source, key)) {
8
- target[key] = source[key];
9
- }
10
- }
11
- }
12
-
13
- return target;
14
- };
15
-
16
- return _extends.apply(this, arguments);
17
- }
18
-
19
- function createContext(init) {
20
- var storage = {
21
- ancestry: []
22
- };
23
- return {
24
- run: run,
25
- bind: bind,
26
- use: use
27
- };
28
-
29
- function run(ctxRef, fn) {
30
- var _init;
31
-
32
- var parentContext = use();
33
-
34
- var out = _extends({}, parentContext ? parentContext : {}, (_init = init === null || init === void 0 ? void 0 : init(ctxRef, parentContext)) !== null && _init !== void 0 ? _init : ctxRef);
35
-
36
- var ctx = set(Object.freeze(out));
37
- storage.ancestry.unshift(ctx);
38
- var res = fn(ctx);
39
- clear();
40
- return res;
41
- }
42
-
43
- function bind(ctxRef, fn) {
44
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
45
- args[_key - 2] = arguments[_key];
46
- }
47
-
48
- return function () {
49
- for (var _len2 = arguments.length, runTimeArgs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
50
- runTimeArgs[_key2] = arguments[_key2];
51
- }
52
-
53
- return run(ctxRef, function () {
54
- return fn.apply(void 0, args.concat(runTimeArgs));
55
- });
56
- };
57
- }
58
-
59
- function use() {
60
- return storage.ctx;
61
- }
62
-
63
- function set(value) {
64
- return storage.ctx = value;
65
- }
66
-
67
- function clear() {
68
- var _storage$ancestry$;
69
-
70
- storage.ancestry.shift();
71
- set((_storage$ancestry$ = storage.ancestry[0]) !== null && _storage$ancestry$ !== void 0 ? _storage$ancestry$ : null);
72
- }
73
- }
74
-
75
- export default createContext;
76
- //# sourceMappingURL=context.esm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context.esm.js","sources":["../src/index.ts"],"sourcesContent":["export default function createContext<T extends Record<string, any>>(\n init?: (ctxRef: T, parentContext: T | void) => T | null\n) {\n const storage: { ctx?: T; ancestry: T[] } = { ancestry: [] };\n\n return {\n run,\n bind,\n use,\n };\n\n function run<R>(ctxRef: T, fn: (context: T) => R): R {\n const parentContext = use();\n\n const out = {\n ...(parentContext ? parentContext : {}),\n ...(init?.(ctxRef, parentContext) ?? ctxRef),\n };\n\n const ctx = set(Object.freeze(out));\n storage.ancestry.unshift(ctx);\n const res = fn(ctx);\n\n clear();\n return res;\n }\n\n function bind<R>(ctxRef: T, fn: (...args: any[]) => R, ...args: any[]) {\n return function(...runTimeArgs: any[]) {\n return run<R>(ctxRef, function() {\n return fn(...args, ...runTimeArgs);\n });\n };\n }\n\n function use() {\n return storage.ctx;\n }\n\n function set(value: T): T {\n return (storage.ctx = value);\n }\n\n function clear() {\n storage.ancestry.shift();\n set(storage.ancestry[0] ?? null);\n }\n}\n"],"names":["createContext","init","storage","ancestry","run","bind","use","ctxRef","fn","parentContext","out","ctx","set","Object","freeze","unshift","res","clear","args","runTimeArgs","value","shift"],"mappings":";;;;;;;;;;;;;;;;;;SAAwBA,cACtBC;AAEA,MAAMC,OAAO,GAA+B;AAAEC,IAAAA,QAAQ,EAAE;AAAZ,GAA5C;AAEA,SAAO;AACLC,IAAAA,GAAG,EAAHA,GADK;AAELC,IAAAA,IAAI,EAAJA,IAFK;AAGLC,IAAAA,GAAG,EAAHA;AAHK,GAAP;;AAMA,WAASF,GAAT,CAAgBG,MAAhB,EAA2BC,EAA3B;;;AACE,QAAMC,aAAa,GAAGH,GAAG,EAAzB;;AAEA,QAAMI,GAAG,gBACHD,aAAa,GAAGA,aAAH,GAAmB,EAD7B,WAEHR,IAFG,aAEHA,IAFG,uBAEHA,IAAI,CAAGM,MAAH,EAAWE,aAAX,CAFD,yCAE8BF,MAF9B,CAAT;;AAKA,QAAMI,GAAG,GAAGC,GAAG,CAACC,MAAM,CAACC,MAAP,CAAcJ,GAAd,CAAD,CAAf;AACAR,IAAAA,OAAO,CAACC,QAAR,CAAiBY,OAAjB,CAAyBJ,GAAzB;AACA,QAAMK,GAAG,GAAGR,EAAE,CAACG,GAAD,CAAd;AAEAM,IAAAA,KAAK;AACL,WAAOD,GAAP;AACD;;AAED,WAASX,IAAT,CAAiBE,MAAjB,EAA4BC,EAA5B;sCAA0DU;AAAAA,MAAAA;;;AACxD,WAAO;yCAAYC;AAAAA,QAAAA;;;AACjB,aAAOf,GAAG,CAAIG,MAAJ,EAAY;AACpB,eAAOC,EAAE,MAAF,SAAMU,IAAN,QAAeC,WAAf,EAAP;AACD,OAFS,CAAV;AAGD,KAJD;AAKD;;AAED,WAASb,GAAT;AACE,WAAOJ,OAAO,CAACS,GAAf;AACD;;AAED,WAASC,GAAT,CAAaQ,KAAb;AACE,WAAQlB,OAAO,CAACS,GAAR,GAAcS,KAAtB;AACD;;AAED,WAASH,KAAT;;;AACEf,IAAAA,OAAO,CAACC,QAAR,CAAiBkB,KAAjB;AACAT,IAAAA,GAAG,uBAACV,OAAO,CAACC,QAAR,CAAiB,CAAjB,CAAD,mEAAwB,IAAxB,CAAH;AACD;AACF;;;;"}
package/dist/index.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export default function createContext<T extends Record<string, any>>(init?: (ctxRef: T, parentContext: T | void) => T | null): {
2
- run: <R>(ctxRef: T, fn: (context: T) => R) => R;
3
- bind: <R_1>(ctxRef: T, fn: (...args: any[]) => R_1, ...args: any[]) => (...runTimeArgs: any[]) => R_1;
4
- use: () => T | undefined;
5
- };
package/dist/index.js DELETED
@@ -1,8 +0,0 @@
1
-
2
- 'use strict'
3
-
4
- if (process.env.NODE_ENV === 'production') {
5
- module.exports = require('./context.cjs.production.min.js')
6
- } else {
7
- module.exports = require('./context.cjs.development.js')
8
- }
package/src/index.ts DELETED
@@ -1,48 +0,0 @@
1
- export default function createContext<T extends Record<string, any>>(
2
- init?: (ctxRef: T, parentContext: T | void) => T | null
3
- ) {
4
- const storage: { ctx?: T; ancestry: T[] } = { ancestry: [] };
5
-
6
- return {
7
- run,
8
- bind,
9
- use,
10
- };
11
-
12
- function run<R>(ctxRef: T, fn: (context: T) => R): R {
13
- const parentContext = use();
14
-
15
- const out = {
16
- ...(parentContext ? parentContext : {}),
17
- ...(init?.(ctxRef, parentContext) ?? ctxRef),
18
- };
19
-
20
- const ctx = set(Object.freeze(out));
21
- storage.ancestry.unshift(ctx);
22
- const res = fn(ctx);
23
-
24
- clear();
25
- return res;
26
- }
27
-
28
- function bind<R>(ctxRef: T, fn: (...args: any[]) => R, ...args: any[]) {
29
- return function(...runTimeArgs: any[]) {
30
- return run<R>(ctxRef, function() {
31
- return fn(...args, ...runTimeArgs);
32
- });
33
- };
34
- }
35
-
36
- function use() {
37
- return storage.ctx;
38
- }
39
-
40
- function set(value: T): T {
41
- return (storage.ctx = value);
42
- }
43
-
44
- function clear() {
45
- storage.ancestry.shift();
46
- set(storage.ancestry[0] ?? null);
47
- }
48
- }