Skip to content

Instantly share code, notes, and snippets.

@enjoylife
Last active August 29, 2022 05:57
Show Gist options
  • Save enjoylife/0b74caecde0521b0565d64d96841cb8c to your computer and use it in GitHub Desktop.
Save enjoylife/0b74caecde0521b0565d64d96841cb8c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Immer
// ...
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e=e||self).immer={})}(this,function(e){"use strict";var r,t="undefined"!=typeof Symbol?Symbol("immer-nothing"):((r={})["immer-nothing"]=!0,r),n="undefined"!=typeof Symbol&&Symbol.for?Symbol.for("immer-draftable"):"__$immer_draftable",o="undefined"!=typeof Symbol&&Symbol.for?Symbol.for("immer-state"):"__$immer_state";function i(e){return!!e&&!!e[o]}function a(e){return!!e&&(function(e){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return!0;var r=Object.getPrototypeOf(e);return!r||r===Object.prototype}(e)||!!e[n]||!!e.constructor[n])}var f=Object.assign||function(e,r){for(var t in r)l(r,t)&&(e[t]=r[t]);return e},s="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames;function c(e,r){if(void 0===r&&(r=!1),Array.isArray(e))return e.slice();var t=Object.create(Object.getPrototypeOf(e));return s(e).forEach(function(n){if(n!==o){var i=Object.getOwnPropertyDescriptor(e,n),a=i.value;if(i.get){if(!r)throw new Error("Immer drafts cannot have computed properties");a=i.get.call(e)}i.enumerable?t[n]=a:Object.defineProperty(t,n,{value:a,writable:!0,configurable:!0})}}),t}function u(e,r){if(Array.isArray(e))for(var t=0;t<e.length;t++)r(t,e[t],e);else s(e).forEach(function(t){return r(t,e[t],e)})}function p(e,r){var t=Object.getOwnPropertyDescriptor(e,r);return!!t&&t.enumerable}function l(e,r){return Object.prototype.hasOwnProperty.call(e,r)}function h(e,r){return e===r?0!==e||1/e==1/r:e!=e&&r!=r}function d(e){if(!a(e))return e;if(Array.isArray(e))return e.map(d);var r=Object.create(Object.getPrototypeOf(e));for(var t in e)r[t]=d(e[t]);return r}function y(e){if(a(e)&&!i(e)&&!Object.isFrozen(e))if(Object.freeze(e),Array.isArray(e))e.forEach(y);else for(var r in e)y(e[r])}var v=function(e){this.drafts=[],this.parent=e,this.canAutoFreeze=!0,this.patches=null};function b(e){e[o].revoke()}v.prototype.usePatches=function(e){e&&(this.patches=[],this.inversePatches=[],this.patchListener=e)},v.prototype.revoke=function(){this.leave(),this.drafts.forEach(b),this.drafts=null},v.prototype.leave=function(){this===v.current&&(v.current=this.parent)},v.current=null,v.enter=function(){return this.current=new v(this.current)};var g={};function m(e,r){var t=Array.isArray(e),n=A(e);u(n,function(r){!function(e,r,t){var n=g[r];n?n.enumerable=t:g[r]=n={configurable:!0,enumerable:t,get:function(){return function(e,r){E(e);var t=O(w(e),r);if(e.finalizing)return t;if(t===O(e.base,r)&&a(t))return j(e),e.copy[r]=m(t,e);return t}(this[o],r)},set:function(e){!function(e,r,t){if(E(e),e.assigned[r]=!0,!e.modified){if(h(t,O(w(e),r)))return;z(e),j(e)}e.copy[r]=t}(this[o],r,e)}};Object.defineProperty(e,r,n)}(n,r,t||p(e,r))});var i,f,s,c=r?r.scope:v.current;return i=n,f=o,s={scope:c,modified:!1,finalizing:!1,finalized:!1,assigned:{},parent:r,base:e,draft:n,copy:null,revoke:P,revoked:!1},Object.defineProperty(i,f,{value:s,enumerable:!1,writable:!0}),c.drafts.push(n),n}function P(){this.revoked=!0}function w(e){return e.copy||e.base}function O(e,r){var t=e[o];if(t&&!t.finalizing){t.finalizing=!0;var n=e[r];return t.finalizing=!1,n}return e[r]}function z(e){e.modified||(e.modified=!0,e.parent&&z(e.parent))}function j(e){e.copy||(e.copy=A(e.base))}function A(e){var r=e&&e[o];if(r){r.finalizing=!0;var t=c(r.draft,!0);return r.finalizing=!1,t}return c(e)}function E(e){if(!0===e.revoked)throw new Error("Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+JSON.stringify(w(e)))}function D(e){for(var r=e.length-1;r>=0;r--){var t=e[r][o];t.modified||(Array.isArray(t.base)?k(t)&&z(t):F(t)&&z(t))}}function F(e){for(var r=e.base,t=e.draft,n=Object.keys(t),i=n.length-1;i>=0;i--){var a=n[i],f=r[a];if(void 0===f&&!l(r,a))return!0;var s=t[a],c=s&&s[o];if(c?c.base!==f:!h(s,f))return!0}return n.length!==Object.keys(r).length}function k(e){var r=e.draft;if(r.length!==e.base.length)return!0;var t=Object.getOwnPropertyDescriptor(r,r.length-1);return!(!t||t.get)}var x=Object.freeze({willFinalize:function(e,r,t){e.drafts.forEach(function(e){e[o].finalizing=!0}),t?i(r)&&r[o].scope===e&&D(e.drafts):(e.patches&&function e(r){if(r&&"object"==typeof r){var t=r[o];if(t){var n=t.base,i=t.draft,a=t.assigned;if(Array.isArray(r)){if(k(t)){if(z(t),a.length=!0,i.length<n.length)for(var f=i.length;f<n.length;f++)a[f]=!1;else for(var s=n.length;s<i.length;s++)a[s]=!0;for(var c=0;c<i.length;c++)void 0===a[c]&&e(i[c])}}else Object.keys(i).forEach(function(r){void 0!==n[r]||l(n,r)?a[r]||e(i[r]):(a[r]=!0,z(t))}),Object.keys(n).forEach(function(e){void 0!==i[e]||l(i,e)||(a[e]=!1,z(t))})}}}(e.drafts[0]),D(e.drafts))},createProxy:m});function R(e,r){var t=r?r.scope:v.current,n={scope:t,modified:!1,finalized:!1,assigned:{},parent:r,base:e,draft:null,drafts:{},copy:null,revoke:null},o=Array.isArray(e)?Proxy.revocable([n],I):Proxy.revocable(n,S),i=o.revoke,a=o.proxy;return n.draft=a,n.revoke=i,t.drafts.push(a),a}var S={get:function(e,r){if(r===o)return e;var t=e.drafts;if(!e.modified&&l(t,r))return t[r];var n=N(e)[r];if(e.finalized||!a(n))return n;if(e.modified){if(n!==_(e.base,r))return n;t=e.copy}return t[r]=R(n,e)},has:function(e,r){return r in N(e)},ownKeys:function(e){return Reflect.ownKeys(N(e))},set:function(e,r,t){if(!e.modified){var n=_(e.base,r),o=t?h(n,t)||t===e.drafts[r]:h(n,t)&&r in e.base;if(o)return!0;T(e)}return e.assigned[r]=!0,e.copy[r]=t,!0},deleteProperty:function(e,r){void 0!==_(e.base,r)||r in e.base?(e.assigned[r]=!1,T(e)):e.assigned[r]&&delete e.assigned[r];e.copy&&delete e.copy[r];return!0},getOwnPropertyDescriptor:function(e,r){var t=N(e),n=Reflect.getOwnPropertyDescriptor(t,r);n&&(n.writable=!0,n.configurable=!Array.isArray(t)||"length"!==r);return n},defineProperty:function(){throw new Error("Object.defineProperty() cannot be used on an Immer draft")},getPrototypeOf:function(e){return Object.getPrototypeOf(e.base)},setPrototypeOf:function(){throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft")}},I={};function N(e){return e.copy||e.base}function _(e,r){var t=e[o],n=Reflect.getOwnPropertyDescriptor(t?N(t):e,r);return n&&n.value}function T(e){e.modified||(e.modified=!0,e.copy=f(c(e.base),e.drafts),e.drafts=null,e.parent&&T(e.parent))}u(S,function(e,r){I[e]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}}),I.deleteProperty=function(e,r){if(isNaN(parseInt(r)))throw new Error("Immer only supports deleting array indices");return S.deleteProperty.call(this,e[0],r)},I.set=function(e,r,t){if("length"!==r&&isNaN(parseInt(r)))throw new Error("Immer only supports setting array indices and the 'length' property");return S.set.call(this,e[0],r,t)};var C=Object.freeze({willFinalize:function(){},createProxy:R});function U(e,r,t,n){Array.isArray(e.base)?function(e,r,t,n){var o,i,a=e.base,f=e.copy,s=e.assigned;f.length<a.length&&(a=(o=[f,a])[0],f=o[1],t=(i=[n,t])[0],n=i[1]);var c=f.length-a.length,u=0;for(;a[u]===f[u]&&u<a.length;)++u;var p=a.length;for(;p>u&&a[p-1]===f[p+c-1];)--p;for(var l=u;l<p;++l)if(s[l]&&f[l]!==a[l]){var h=r.concat([l]);t.push({op:"replace",path:h,value:f[l]}),n.push({op:"replace",path:h,value:a[l]})}for(var d=t.length,y=p+c-1;y>=p;--y){var v=r.concat([y]);t[d+y-p]={op:"add",path:v,value:f[y]},n.push({op:"remove",path:v})}}(e,r,t,n):function(e,r,t,n){var o=e.base,i=e.copy;u(e.assigned,function(e,a){var f=o[e],s=i[e],c=a?e in o?"replace":"add":"remove";if(f!==s||"replace"!==c){var u=r.concat(e);t.push("remove"===c?{op:c,path:u}:{op:c,path:u,value:s}),n.push("add"===c?{op:"remove",path:u}:"remove"===c?{op:"add",path:u,value:f}:{op:"replace",path:u,value:f})}})}(e,r,t,n)}var W=function(e,r){for(var t=0,n=r;t<n.length;t+=1){var o=n[t],i=o.path,a=o.op,f=d(o.value);if(!i.length)throw new Error("Illegal state");for(var s=e,c=0;c<i.length-1;c++)if(!(s=s[i[c]])||"object"!=typeof s)throw new Error("Cannot apply patch, path doesn't resolve: "+i.join("/"));var u=i[i.length-1];switch(a){case"replace":s[u]=f;break;case"add":Array.isArray(s)?s.splice(u,0,f):s[u]=f;break;case"remove":Array.isArray(s)?s.splice(u,1):delete s[u];break;default:throw new Error("Unsupported patch operation: "+a)}}return e};var K={useProxies:"undefined"!=typeof Proxy&&"undefined"!=typeof Reflect,autoFreeze:"undefined"!=typeof process?"production"!==process.env.NODE_ENV:"verifyMinified"===function(){}.name,onAssign:null,onDelete:null,onCopy:null},M=function(e){f(this,K,e),this.setUseProxies(this.useProxies),this.produce=this.produce.bind(this)};M.prototype.produce=function(e,r,n){var o,i=this;if("function"==typeof e&&"function"!=typeof r){var f=r;r=e;var s=this;return function(e){var t=this;void 0===e&&(e=f);for(var n=[],o=arguments.length-1;o-- >0;)n[o]=arguments[o+1];return s.produce(e,function(e){return r.call.apply(r,[t,e].concat(n))})}}if("function"!=typeof r)throw new Error("The first or second argument to `produce` must be a function");if(void 0!==n&&"function"!=typeof n)throw new Error("The third argument to `produce` must be a function or undefined");if(a(e)){var c=v.enter(),u=this.createProxy(e),p=!0;try{o=r(u),p=!1}finally{p?c.revoke():c.leave()}return o instanceof Promise?o.then(function(e){return c.usePatches(n),i.processResult(e,c)},function(e){throw c.revoke(),e}):(c.usePatches(n),this.processResult(o,c))}if((o=r(e))!==t)return void 0===o&&(o=e),this.maybeFreeze(o,!0),o},M.prototype.produceWithPatches=function(e,r,t){var n,o,i=this;if("function"==typeof e)return function(r){for(var t=[],n=arguments.length-1;n-- >0;)t[n]=arguments[n+1];return i.produceWithPatches(r,function(r){return e.apply(void 0,[r].concat(t))})};if(t)throw new Error("A patch listener cannot be passed to produceWithPatches");return[this.produce(e,r,function(e,r){n=e,o=r}),n,o]},M.prototype.createDraft=function(e){if(!a(e))throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object");var r=v.enter(),t=this.createProxy(e);return t[o].isManual=!0,r.leave(),t},M.prototype.finishDraft=function(e,r){var t=e&&e[o];if(!t||!t.isManual)throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`");if(t.finalized)throw new Error("The given draft is already finalized");var n=t.scope;return n.usePatches(r),this.processResult(void 0,n)},M.prototype.setAutoFreeze=function(e){this.autoFreeze=e},M.prototype.setUseProxies=function(e){this.useProxies=e,f(this,e?C:x)},M.prototype.applyPatches=function(e,r){var t;for(t=r.length-1;t>=0;t--){var n=r[t];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}return i(e)?W(e,r):this.produce(e,function(e){return W(e,r.slice(t+1))})},M.prototype.processResult=function(e,r){var n=r.drafts[0],i=void 0!==e&&e!==n;if(this.willFinalize(r,e,i),i){if(n[o].modified)throw r.revoke(),new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.");a(e)&&(e=this.finalize(e,null,r),this.maybeFreeze(e)),r.patches&&(r.patches.push({op:"replace",path:[],value:e}),r.inversePatches.push({op:"replace",path:[],value:n[o].base}))}else e=this.finalize(n,[],r);return r.revoke(),r.patches&&r.patchListener(r.patches,r.inversePatches),e!==t?e:void 0},M.prototype.finalize=function(e,r,t){var n=this,i=e[o];if(!i)return Object.isFrozen(e)?e:this.finalizeTree(e,null,t);if(i.scope!==t)return e;if(!i.modified)return this.maybeFreeze(i.base,!0),i.base;if(!i.finalized){if(i.finalized=!0,this.finalizeTree(i.draft,r,t),this.onDelete)if(this.useProxies){var a=i.assigned;for(var f in a)a[f]||this.onDelete(i,f)}else{var s=i.base,c=i.copy;u(s,function(e){l(c,e)||n.onDelete(i,e)})}this.onCopy&&this.onCopy(i),this.autoFreeze&&t.canAutoFreeze&&Object.freeze(i.copy),r&&t.patches&&U(i,r,t.patches,t.inversePatches)}return i.copy},M.prototype.finalizeTree=function(e,r,t){var n=this,f=e[o];f&&(this.useProxies||(f.copy=c(f.draft,!0)),e=f.copy);var s=!!r&&!!t.patches,l=function(o,c,d){if(c===d)throw Error("Immer forbids circular references");var y=!!f&&d===e;if(i(c)){var v=y&&s&&!f.assigned[o]?r.concat(o):null;if(i(c=n.finalize(c,v,t))&&(t.canAutoFreeze=!1),Array.isArray(d)||p(d,o)?d[o]=c:Object.defineProperty(d,o,{value:c}),y&&c===f.base[o])return}else{if(y&&h(c,f.base[o]))return;a(c)&&!Object.isFrozen(c)&&(u(c,l),n.maybeFreeze(c))}y&&n.onAssign&&n.onAssign(f,o,c)};return u(e,l),e},M.prototype.maybeFreeze=function(e,r){void 0===r&&(r=!1),this.autoFreeze&&!i(e)&&(r?y(e):Object.freeze(e))};var L=new M,$=L.produce,J=L.produceWithPatches.bind(L),V=L.setAutoFreeze.bind(L),q=L.setUseProxies.bind(L),B=L.applyPatches.bind(L),G=L.createDraft.bind(L),H=L.finishDraft.bind(L);e.Immer=M,e.applyPatches=B,e.createDraft=G,e.default=$,e.finishDraft=H,e.immerable=n,e.isDraft=i,e.isDraftable=a,e.nothing=t,e.original=function(e){if(e&&e[o])return e[o].base},e.produce=$,e.produceWithPatches=J,e.setAutoFreeze=V,e.setUseProxies=q,Object.defineProperty(e,"__esModule",{value:!0})});
// END Immer
// We don't have access to a es6 environment
const produce = immer.produce
const VERBOSE = false;
const {cancel} = actions
// END PRE SETUP
function editAction(produceFn) {
return assign((context, event) => {
return produce(context, draft => produceFn(draft, event));
});
}
function fakeSyncFetch(changes) {
const p = new Promise((resolve, reject) => {
VERBOSE && console.log('pending sync fetch', changes);
setTimeout(() => {
VERBOSE && console.log('success', changes);
resolve({accepted: changes});
}, 10);
});
return p;
}
const repush = send('SUCCESS', {
id: 'repushTimer',
delay: (context, event) => {
const timeDelta = Date.now() - context.lastStart;
let remaining = 0;
// has enough time passed?
if (timeDelta < context.throttle) {
remaining = context.throttle - timeDelta;
}
VERBOSE && console.log('delay pause', remaining);
return remaining;
},
});
const cancelTimer = cancel('repushTimer'); // pass the ID of event to cancel
const pusher = Machine(
{
id: 'pusher',
initial: 'idle',
context: {
changes: [],
error: null,
lastStart: null,
throttle: 50,
maxQueuedChanges: 5,
},
states: {
idle: {
on: {
CHANGE: [{target: 'pushing', actions: ['queueChange']}],
},
exit: ['cancelTimer'],
},
error: {
on: {
RETRY: [{target: 'pushing'}],
},
},
pushing: {
on: {
STOP: {target: 'idle'},
// more changes will be queued up while we have an
// ongoing fetch being made
CHANGE: [{cond: 'canQueue', actions: ['queueChange']}],
SUCCESS: [
{
cond: 'moreToPush',
target: 'pushing', // we want to reinvoke our promise
},
{
target: 'idle',
actions: 'backToIdle',
},
],
},
entry: ['setLastStart'],
exit: ['cancelTimer'],
// If we go the promise route...
invoke: {
id: 'fetchCall',
src: (context, event) => fakeSyncFetch(context.changes),
// only takes one, can'd have [{cond},{cond}] :(
onDone: {
target: 'pushing',
internal: true,
actions: ['removeAccepted', 'repush'],
// actions: ['removeAccepted', raise('CHANGE')],
/* todo: throttle delay send... */
// delay: (context, event) {}
},
onError: [
{
// cond: '',
target: 'error',
actions: ['addErr'],
},
],
},
},
},
},
{
actions: {
queueChange: editAction((context, event) => {
if (event.change) {
context.changes.push(event.change);
}
VERBOSE && console.log('queueChange', context.changes);
}),
errQueueFull: editAction((context, event) => {
context.error = new Error(
`queue is full with ${context.maxQueuedChanges} changes`
);
}),
removeAccepted: editAction((context, event) => {
const acceptedLen =
event.data && event.data.accepted && event.data.accepted.length
? event.data.accepted.length
: 0;
VERBOSE && console.log('removeAccepted', event);
if (acceptedLen) {
context.changes = context.changes.splice(acceptedLen);
}
}),
setLastStart: editAction((context, event) => {
VERBOSE && console.log('setLastStart');
context.lastStart = Date.now();
}),
addErr: editAction((context, event) => {
VERBOSE && console.log('addErr', event);
context.error = event.data;
}),
backToIdle: editAction((context, event) => {
VERBOSE && console.log('backToIdle', context.value, event);
}),
repush: repush,
cancelTimer: cancelTimer,
},
guards: {
canQueue: (context, event) => {
// console.log('canQueue', event);
return context.maxQueuedChanges > context.changes.length;
},
moreToPush: (context, event) => {
VERBOSE && console.log('moreToPush', context, event);
return context.changes.length > 0;
},
queueFull: context => {
return context.maxQueuedChanges <= context.changes.length;
},
},
}
);
// BEGIN LIBRARY HELPERS
@robskiesarbsa
Copy link

const car = "Dodge Charger";
const someObject = { str: "Some text", id: 5 };
console.info("My first car was a", car, ". The object is:", someObject);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment