MCPcopy Create free account
hub / github.com/Snapchat/Valdi / doPostInit

Method doPostInit

valdi/src/valdi/runtime/JavaScript/JavaScriptWorker.cpp:74–111  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

72}
73
74void JavaScriptWorker::doPostInit() {
75 auto weakSelf = weakRef(this);
76 // Set up globals in the worker runtime
77 // - onmessage
78 // - postMessage
79 // - close
80 // - location, https://developer.mozilla.org/en-US/docs/Web/API/WorkerLocation, only href and search are populated
81 _runtime->setValueToGlobalObject(STRING_LITERAL("onmessage"), Value::undefined());
82 auto postMessageFunc = [weakSelf](const ValueFunctionCallContext& callContext) -> Value {
83 auto self = weakSelf.lock();
84 if (self && !self->_closed) {
85 dispatchMessage(self->_hostOnMessage, callContext.getParameter(0));
86 }
87 return Value::undefined();
88 };
89 _runtime->setValueToGlobalObject(STRING_LITERAL("postMessage"),
90 Value(makeShared<ValueFunctionWithCallable>(postMessageFunc)));
91 auto closeFunc = [weakSelf](const ValueFunctionCallContext& callContext) -> Value {
92 auto self = weakSelf.lock();
93 if (self) {
94 self->close();
95 }
96 return Value::undefined();
97 };
98
99 _runtime->setValueToGlobalObject(STRING_LITERAL("close"), Value(makeShared<ValueFunctionWithCallable>(closeFunc)));
100
101 auto queryStartIndex = _url.indexOf('?');
102 auto scriptUrl = queryStartIndex.has_value() ? _url.substring(0, queryStartIndex.value()) : _url;
103 auto location = makeShared<ValueMap>();
104 (*location)[STRING_LITERAL("href")] = Value(_url);
105 (*location)[STRING_LITERAL("search")] =
106 Value(queryStartIndex.has_value() ? _url.substring(queryStartIndex.value()) : STRING_LITERAL(""));
107 _runtime->setValueToGlobalObject(STRING_LITERAL("location"), Value(location));
108
109 // Evaluate the worker script
110 auto result = _runtime->evalModuleSync(scriptUrl, false);
111}
112
113void JavaScriptWorker::doSetHostOnMessage(const Ref<ValueFunction>& func) {
114 _hostOnMessage = func;

Callers 1

postInitMethod · 0.95

Calls 12

closeMethod · 0.95
weakRefFunction · 0.85
dispatchMessageFunction · 0.85
getParameterMethod · 0.80
substringMethod · 0.80
evalModuleSyncMethod · 0.80
valueMethod · 0.65
ValueClass · 0.50
lockMethod · 0.45
indexOfMethod · 0.45
has_valueMethod · 0.45

Tested by

no test coverage detected