├── .editorconfig
├── .gitignore
├── Directory.Build.props
├── LICENSE
├── Microsoft.JSInterop.sln
├── README.md
├── build
└── Key.snk
├── src
├── Microsoft.JSInterop.JS
│ ├── .gitignore
│ ├── Microsoft.JSInterop.JS.csproj
│ ├── package-lock.json
│ ├── package.json
│ ├── src
│ │ └── Microsoft.JSInterop.ts
│ └── tsconfig.json
├── Microsoft.JSInterop
│ ├── DotNetDispatcher.cs
│ ├── DotNetObjectRef.cs
│ ├── ICustomArgSerializer.cs
│ ├── IJSInProcessRuntime.cs
│ ├── IJSRuntime.cs
│ ├── InteropArgSerializerStrategy.cs
│ ├── JSAsyncCallResult.cs
│ ├── JSException.cs
│ ├── JSInProcessRuntimeBase.cs
│ ├── JSInvokableAttribute.cs
│ ├── JSRuntime.cs
│ ├── JSRuntimeBase.cs
│ ├── Json
│ │ ├── CamelCase.cs
│ │ ├── Json.cs
│ │ └── SimpleJson
│ │ │ ├── README.txt
│ │ │ └── SimpleJson.cs
│ ├── Microsoft.JSInterop.csproj
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── TaskGenericsUtil.cs
└── Mono.WebAssembly.Interop
│ ├── InternalCalls.cs
│ ├── Mono.WebAssembly.Interop.csproj
│ └── MonoWebAssemblyJSRuntime.cs
└── test
└── Microsoft.JSInterop.Test
├── DotNetDispatcherTest.cs
├── DotNetObjectRefTest.cs
├── JSInProcessRuntimeBaseTest.cs
├── JSRuntimeBaseTest.cs
├── JSRuntimeTest.cs
├── JsonUtilTest.cs
└── Microsoft.JSInterop.Test.csproj
/.editorconfig:
--------------------------------------------------------------------------------
1 | # All Files
2 | [*]
3 | charset = utf-8
4 | end_of_line = crlf
5 | indent_style = space
6 | indent_size = 4
7 | insert_final_newline = false
8 | trim_trailing_whitespace = true
9 |
10 | # Solution Files
11 | [*.sln]
12 | indent_style = tab
13 |
14 | # Markdown Files
15 | [*.md]
16 | trim_trailing_whitespace = false
17 |
18 | # Web Files
19 | [*.{htm,html,js,ts,css,scss,less}]
20 | insert_final_newline = true
21 | indent_size = 2
22 |
23 | [*.{yml,json}]
24 | indent_size = 2
25 |
26 | [*.{xml,csproj,config,*proj,targets,props}]
27 | indent_size = 2
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | $(MSBuildThisFileDirectory)build\Key.snk
6 | true
7 | true
8 | Microsoft
9 | 7.3
10 |
11 |
12 |
13 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Microsoft.JSInterop.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27703.2042
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1290437E-A890-419E-A317-D0F7FEE185A5}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{B98D4F51-88FB-471C-B56F-752E8EE502E7}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.JSInterop", "src\Microsoft.JSInterop\Microsoft.JSInterop.csproj", "{CB4CD4A6-9BAA-46D1-944F-CE56DEC2663C}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.JSInterop.Test", "test\Microsoft.JSInterop.Test\Microsoft.JSInterop.Test.csproj", "{7FF8B199-52C0-4DFE-A73B-0C9E18220C0E}"
13 | EndProject
14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.JSInterop.JS", "src\Microsoft.JSInterop.JS\Microsoft.JSInterop.JS.csproj", "{60BA5AAD-264A-437E-8319-577841C66CC6}"
15 | EndProject
16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{BE4CBB33-5C40-4A07-B6FC-1D7C3AE13024}"
17 | ProjectSection(SolutionItems) = preProject
18 | README.md = README.md
19 | EndProjectSection
20 | EndProject
21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mono.WebAssembly.Interop", "src\Mono.WebAssembly.Interop\Mono.WebAssembly.Interop.csproj", "{10145E99-1B2D-40C5-9595-582BDAF3E024}"
22 | EndProject
23 | Global
24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
25 | Debug|Any CPU = Debug|Any CPU
26 | Release|Any CPU = Release|Any CPU
27 | EndGlobalSection
28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
29 | {CB4CD4A6-9BAA-46D1-944F-CE56DEC2663C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {CB4CD4A6-9BAA-46D1-944F-CE56DEC2663C}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {CB4CD4A6-9BAA-46D1-944F-CE56DEC2663C}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {CB4CD4A6-9BAA-46D1-944F-CE56DEC2663C}.Release|Any CPU.Build.0 = Release|Any CPU
33 | {7FF8B199-52C0-4DFE-A73B-0C9E18220C0E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
34 | {7FF8B199-52C0-4DFE-A73B-0C9E18220C0E}.Debug|Any CPU.Build.0 = Debug|Any CPU
35 | {7FF8B199-52C0-4DFE-A73B-0C9E18220C0E}.Release|Any CPU.ActiveCfg = Release|Any CPU
36 | {7FF8B199-52C0-4DFE-A73B-0C9E18220C0E}.Release|Any CPU.Build.0 = Release|Any CPU
37 | {60BA5AAD-264A-437E-8319-577841C66CC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
38 | {60BA5AAD-264A-437E-8319-577841C66CC6}.Debug|Any CPU.Build.0 = Debug|Any CPU
39 | {60BA5AAD-264A-437E-8319-577841C66CC6}.Release|Any CPU.ActiveCfg = Release|Any CPU
40 | {60BA5AAD-264A-437E-8319-577841C66CC6}.Release|Any CPU.Build.0 = Release|Any CPU
41 | {10145E99-1B2D-40C5-9595-582BDAF3E024}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42 | {10145E99-1B2D-40C5-9595-582BDAF3E024}.Debug|Any CPU.Build.0 = Debug|Any CPU
43 | {10145E99-1B2D-40C5-9595-582BDAF3E024}.Release|Any CPU.ActiveCfg = Release|Any CPU
44 | {10145E99-1B2D-40C5-9595-582BDAF3E024}.Release|Any CPU.Build.0 = Release|Any CPU
45 | EndGlobalSection
46 | GlobalSection(SolutionProperties) = preSolution
47 | HideSolutionNode = FALSE
48 | EndGlobalSection
49 | GlobalSection(NestedProjects) = preSolution
50 | {CB4CD4A6-9BAA-46D1-944F-CE56DEC2663C} = {1290437E-A890-419E-A317-D0F7FEE185A5}
51 | {7FF8B199-52C0-4DFE-A73B-0C9E18220C0E} = {B98D4F51-88FB-471C-B56F-752E8EE502E7}
52 | {60BA5AAD-264A-437E-8319-577841C66CC6} = {1290437E-A890-419E-A317-D0F7FEE185A5}
53 | {10145E99-1B2D-40C5-9595-582BDAF3E024} = {1290437E-A890-419E-A317-D0F7FEE185A5}
54 | EndGlobalSection
55 | GlobalSection(ExtensibilityGlobals) = postSolution
56 | SolutionGuid = {7E07ABF2-427A-43FA-A6A4-82B21B96ACAF}
57 | EndGlobalSection
58 | EndGlobal
59 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # jsinterop [ARCHIVED]
2 |
3 | ## Please go to https://github.com/aspnet/Extensions/tree/master/src/JSInterop to see the latest JSInterop code base and to file issues
4 |
5 | This repo is for `Microsoft.JSInterop`, a package that provides abstractions and features for interop between .NET and JavaScript code.
6 |
7 | ## Usage
8 |
9 | The primary use case is for applications built with Mono WebAssembly or Blazor. It's not expected that developers will typically use these libraries separately from Mono WebAssembly, Blazor, or a similar technology.
10 |
11 | ## How to build and test
12 |
13 | To build:
14 |
15 | 1. Ensure you have installed an up-to-date version of the [.NET Core SDK](https://www.microsoft.com/net/download). To verify, run `dotnet --version` and be sure that it returns `2.1.300` (i.e., .NET Core 2.1) or later.
16 | 2. Run `dotnet build`
17 |
18 | To run tests:
19 |
20 | 1. Run `dotnet test test/Microsoft.JSInterop.Test`
21 |
--------------------------------------------------------------------------------
/build/Key.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dotnet/jsinterop/8495c8bb132d3c92a5e4a3a9d4bbf1ad06fb9992/build/Key.snk
--------------------------------------------------------------------------------
/src/Microsoft.JSInterop.JS/.gitignore:
--------------------------------------------------------------------------------
1 | dist/
2 |
--------------------------------------------------------------------------------
/src/Microsoft.JSInterop.JS/Microsoft.JSInterop.JS.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | Latest
6 | false
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/Microsoft.JSInterop.JS/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@dotnet/jsinterop",
3 | "version": "0.1.1",
4 | "lockfileVersion": 1,
5 | "requires": true,
6 | "dependencies": {
7 | "balanced-match": {
8 | "version": "1.0.0",
9 | "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
10 | "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
11 | "dev": true
12 | },
13 | "brace-expansion": {
14 | "version": "1.1.11",
15 | "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
16 | "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
17 | "dev": true,
18 | "requires": {
19 | "balanced-match": "1.0.0",
20 | "concat-map": "0.0.1"
21 | }
22 | },
23 | "concat-map": {
24 | "version": "0.0.1",
25 | "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
26 | "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
27 | "dev": true
28 | },
29 | "fs.realpath": {
30 | "version": "1.0.0",
31 | "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
32 | "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
33 | "dev": true
34 | },
35 | "glob": {
36 | "version": "7.1.3",
37 | "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz",
38 | "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==",
39 | "dev": true,
40 | "requires": {
41 | "fs.realpath": "1.0.0",
42 | "inflight": "1.0.6",
43 | "inherits": "2.0.3",
44 | "minimatch": "3.0.4",
45 | "once": "1.4.0",
46 | "path-is-absolute": "1.0.1"
47 | }
48 | },
49 | "inflight": {
50 | "version": "1.0.6",
51 | "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
52 | "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
53 | "dev": true,
54 | "requires": {
55 | "once": "1.4.0",
56 | "wrappy": "1.0.2"
57 | }
58 | },
59 | "inherits": {
60 | "version": "2.0.3",
61 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
62 | "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
63 | "dev": true
64 | },
65 | "minimatch": {
66 | "version": "3.0.4",
67 | "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
68 | "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
69 | "dev": true,
70 | "requires": {
71 | "brace-expansion": "1.1.11"
72 | }
73 | },
74 | "once": {
75 | "version": "1.4.0",
76 | "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
77 | "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
78 | "dev": true,
79 | "requires": {
80 | "wrappy": "1.0.2"
81 | }
82 | },
83 | "path-is-absolute": {
84 | "version": "1.0.1",
85 | "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
86 | "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
87 | "dev": true
88 | },
89 | "rimraf": {
90 | "version": "2.6.2",
91 | "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz",
92 | "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==",
93 | "dev": true,
94 | "requires": {
95 | "glob": "7.1.3"
96 | }
97 | },
98 | "wrappy": {
99 | "version": "1.0.2",
100 | "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
101 | "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
102 | "dev": true
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/Microsoft.JSInterop.JS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@dotnet/jsinterop",
3 | "version": "0.1.1",
4 | "description": "Provides abstractions and features for interop between .NET and JavaScript code.",
5 | "main": "dist/Microsoft.JSInterop.js",
6 | "types": "dist/Microsoft.JSInterop.d.js",
7 | "scripts": {
8 | "prepublish": "rimraf dist && dotnet build && echo 'Finished building NPM package \"@dotnet/jsinterop\"'"
9 | },
10 | "files": [
11 | "dist/**"
12 | ],
13 | "author": "Microsoft",
14 | "license": "Apache-2.0",
15 | "bugs": {
16 | "url": "https://github.com/dotnet/jsinterop/issues"
17 | },
18 | "repository": {
19 | "type": "git",
20 | "url": "https://github.com/dotnet/jsinterop.git"
21 | },
22 | "devDependencies": {
23 | "rimraf": "^2.5.4"
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/Microsoft.JSInterop.JS/src/Microsoft.JSInterop.ts:
--------------------------------------------------------------------------------
1 | // This is a single-file self-contained module to avoid the need for a Webpack build
2 |
3 | module DotNet {
4 | (window as any).DotNet = DotNet; // Ensure reachable from anywhere
5 |
6 | export type JsonReviver = ((key: any, value: any) => any);
7 | const jsonRevivers: JsonReviver[] = [];
8 |
9 | const pendingAsyncCalls: { [id: number]: PendingAsyncCall } = {};
10 | const cachedJSFunctions: { [identifier: string]: Function } = {};
11 | let nextAsyncCallId = 1; // Start at 1 because zero signals "no response needed"
12 |
13 | let dotNetDispatcher: DotNetCallDispatcher | null = null;
14 |
15 | /**
16 | * Sets the specified .NET call dispatcher as the current instance so that it will be used
17 | * for future invocations.
18 | *
19 | * @param dispatcher An object that can dispatch calls from JavaScript to a .NET runtime.
20 | */
21 | export function attachDispatcher(dispatcher: DotNetCallDispatcher) {
22 | dotNetDispatcher = dispatcher;
23 | }
24 |
25 | /**
26 | * Adds a JSON reviver callback that will be used when parsing arguments received from .NET.
27 | * @param reviver The reviver to add.
28 | */
29 | export function attachReviver(reviver: JsonReviver) {
30 | jsonRevivers.push(reviver);
31 | }
32 |
33 | /**
34 | * Invokes the specified .NET public method synchronously. Not all hosting scenarios support
35 | * synchronous invocation, so if possible use invokeMethodAsync instead.
36 | *
37 | * @param assemblyName The short name (without key/version or .dll extension) of the .NET assembly containing the method.
38 | * @param methodIdentifier The identifier of the method to invoke. The method must have a [JSInvokable] attribute specifying this identifier.
39 | * @param args Arguments to pass to the method, each of which must be JSON-serializable.
40 | * @returns The result of the operation.
41 | */
42 | export function invokeMethod(assemblyName: string, methodIdentifier: string, ...args: any[]): T {
43 | return invokePossibleInstanceMethod(assemblyName, methodIdentifier, null, args);
44 | }
45 |
46 | /**
47 | * Invokes the specified .NET public method asynchronously.
48 | *
49 | * @param assemblyName The short name (without key/version or .dll extension) of the .NET assembly containing the method.
50 | * @param methodIdentifier The identifier of the method to invoke. The method must have a [JSInvokable] attribute specifying this identifier.
51 | * @param args Arguments to pass to the method, each of which must be JSON-serializable.
52 | * @returns A promise representing the result of the operation.
53 | */
54 | export function invokeMethodAsync(assemblyName: string, methodIdentifier: string, ...args: any[]): Promise {
55 | return invokePossibleInstanceMethodAsync(assemblyName, methodIdentifier, null, args);
56 | }
57 |
58 | function invokePossibleInstanceMethod(assemblyName: string | null, methodIdentifier: string, dotNetObjectId: number | null, args: any[]): T {
59 | const dispatcher = getRequiredDispatcher();
60 | if (dispatcher.invokeDotNetFromJS) {
61 | const argsJson = JSON.stringify(args, argReplacer);
62 | const resultJson = dispatcher.invokeDotNetFromJS(assemblyName, methodIdentifier, dotNetObjectId, argsJson);
63 | return resultJson ? parseJsonWithRevivers(resultJson) : null;
64 | } else {
65 | throw new Error('The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead.');
66 | }
67 | }
68 |
69 | function invokePossibleInstanceMethodAsync(assemblyName: string | null, methodIdentifier: string, dotNetObjectId: number | null, args: any[]): Promise {
70 | const asyncCallId = nextAsyncCallId++;
71 | const resultPromise = new Promise((resolve, reject) => {
72 | pendingAsyncCalls[asyncCallId] = { resolve, reject };
73 | });
74 |
75 | try {
76 | const argsJson = JSON.stringify(args, argReplacer);
77 | getRequiredDispatcher().beginInvokeDotNetFromJS(asyncCallId, assemblyName, methodIdentifier, dotNetObjectId, argsJson);
78 | } catch(ex) {
79 | // Synchronous failure
80 | completePendingCall(asyncCallId, false, ex);
81 | }
82 |
83 | return resultPromise;
84 | }
85 |
86 | function getRequiredDispatcher(): DotNetCallDispatcher {
87 | if (dotNetDispatcher !== null) {
88 | return dotNetDispatcher;
89 | }
90 |
91 | throw new Error('No .NET call dispatcher has been set.');
92 | }
93 |
94 | function completePendingCall(asyncCallId: number, success: boolean, resultOrError: any) {
95 | if (!pendingAsyncCalls.hasOwnProperty(asyncCallId)) {
96 | throw new Error(`There is no pending async call with ID ${asyncCallId}.`);
97 | }
98 |
99 | const asyncCall = pendingAsyncCalls[asyncCallId];
100 | delete pendingAsyncCalls[asyncCallId];
101 | if (success) {
102 | asyncCall.resolve(resultOrError);
103 | } else {
104 | asyncCall.reject(resultOrError);
105 | }
106 | }
107 |
108 | interface PendingAsyncCall {
109 | resolve: (value?: T | PromiseLike) => void;
110 | reject: (reason?: any) => void;
111 | }
112 |
113 | /**
114 | * Represents the ability to dispatch calls from JavaScript to a .NET runtime.
115 | */
116 | export interface DotNetCallDispatcher {
117 | /**
118 | * Optional. If implemented, invoked by the runtime to perform a synchronous call to a .NET method.
119 | *
120 | * @param assemblyName The short name (without key/version or .dll extension) of the .NET assembly holding the method to invoke. The value may be null when invoking instance methods.
121 | * @param methodIdentifier The identifier of the method to invoke. The method must have a [JSInvokable] attribute specifying this identifier.
122 | * @param dotNetObjectId If given, the call will be to an instance method on the specified DotNetObject. Pass null or undefined to call static methods.
123 | * @param argsJson JSON representation of arguments to pass to the method.
124 | * @returns JSON representation of the result of the invocation.
125 | */
126 | invokeDotNetFromJS?(assemblyName: string | null, methodIdentifier: string, dotNetObjectId: number | null, argsJson: string): string | null;
127 |
128 | /**
129 | * Invoked by the runtime to begin an asynchronous call to a .NET method.
130 | *
131 | * @param callId A value identifying the asynchronous operation. This value should be passed back in a later call from .NET to JS.
132 | * @param assemblyName The short name (without key/version or .dll extension) of the .NET assembly holding the method to invoke. The value may be null when invoking instance methods.
133 | * @param methodIdentifier The identifier of the method to invoke. The method must have a [JSInvokable] attribute specifying this identifier.
134 | * @param dotNetObjectId If given, the call will be to an instance method on the specified DotNetObject. Pass null to call static methods.
135 | * @param argsJson JSON representation of arguments to pass to the method.
136 | */
137 | beginInvokeDotNetFromJS(callId: number, assemblyName: string | null, methodIdentifier: string, dotNetObjectId: number | null, argsJson: string): void;
138 | }
139 |
140 | /**
141 | * Receives incoming calls from .NET and dispatches them to JavaScript.
142 | */
143 | export const jsCallDispatcher = {
144 | /**
145 | * Finds the JavaScript function matching the specified identifier.
146 | *
147 | * @param identifier Identifies the globally-reachable function to be returned.
148 | * @returns A Function instance.
149 | */
150 | findJSFunction,
151 |
152 | /**
153 | * Invokes the specified synchronous JavaScript function.
154 | *
155 | * @param identifier Identifies the globally-reachable function to invoke.
156 | * @param argsJson JSON representation of arguments to be passed to the function.
157 | * @returns JSON representation of the invocation result.
158 | */
159 | invokeJSFromDotNet: (identifier: string, argsJson: string) => {
160 | const result = findJSFunction(identifier).apply(null, parseJsonWithRevivers(argsJson));
161 | return result === null || result === undefined
162 | ? null
163 | : JSON.stringify(result, argReplacer);
164 | },
165 |
166 | /**
167 | * Invokes the specified synchronous or asynchronous JavaScript function.
168 | *
169 | * @param asyncHandle A value identifying the asynchronous operation. This value will be passed back in a later call to endInvokeJSFromDotNet.
170 | * @param identifier Identifies the globally-reachable function to invoke.
171 | * @param argsJson JSON representation of arguments to be passed to the function.
172 | */
173 | beginInvokeJSFromDotNet: (asyncHandle: number, identifier: string, argsJson: string): void => {
174 | // Coerce synchronous functions into async ones, plus treat
175 | // synchronous exceptions the same as async ones
176 | const promise = new Promise(resolve => {
177 | const synchronousResultOrPromise = findJSFunction(identifier).apply(null, parseJsonWithRevivers(argsJson));
178 | resolve(synchronousResultOrPromise);
179 | });
180 |
181 | // We only listen for a result if the caller wants to be notified about it
182 | if (asyncHandle) {
183 | // On completion, dispatch result back to .NET
184 | // Not using "await" because it codegens a lot of boilerplate
185 | promise.then(
186 | result => getRequiredDispatcher().beginInvokeDotNetFromJS(0, 'Microsoft.JSInterop', 'DotNetDispatcher.EndInvoke', null, JSON.stringify([asyncHandle, true, result], argReplacer)),
187 | error => getRequiredDispatcher().beginInvokeDotNetFromJS(0, 'Microsoft.JSInterop', 'DotNetDispatcher.EndInvoke', null, JSON.stringify([asyncHandle, false, formatError(error)]))
188 | );
189 | }
190 | },
191 |
192 | /**
193 | * Receives notification that an async call from JS to .NET has completed.
194 | * @param asyncCallId The identifier supplied in an earlier call to beginInvokeDotNetFromJS.
195 | * @param success A flag to indicate whether the operation completed successfully.
196 | * @param resultOrExceptionMessage Either the operation result or an error message.
197 | */
198 | endInvokeDotNetFromJS: (asyncCallId: string, success: boolean, resultOrExceptionMessage: any): void => {
199 | const resultOrError = success ? resultOrExceptionMessage : new Error(resultOrExceptionMessage);
200 | completePendingCall(parseInt(asyncCallId), success, resultOrError);
201 | }
202 | }
203 |
204 | function parseJsonWithRevivers(json: string): any {
205 | return json ? JSON.parse(json, (key, initialValue) => {
206 | // Invoke each reviver in order, passing the output from the previous reviver,
207 | // so that each one gets a chance to transform the value
208 | return jsonRevivers.reduce(
209 | (latestValue, reviver) => reviver(key, latestValue),
210 | initialValue
211 | );
212 | }) : null;
213 | }
214 |
215 | function formatError(error: any): string {
216 | if (error instanceof Error) {
217 | return `${error.message}\n${error.stack}`;
218 | } else {
219 | return error ? error.toString() : 'null';
220 | }
221 | }
222 |
223 | function findJSFunction(identifier: string): Function {
224 | if (cachedJSFunctions.hasOwnProperty(identifier)) {
225 | return cachedJSFunctions[identifier];
226 | }
227 |
228 | let result: any = window;
229 | let resultIdentifier = 'window';
230 | identifier.split('.').forEach(segment => {
231 | if (segment in result) {
232 | result = result[segment];
233 | resultIdentifier += '.' + segment;
234 | } else {
235 | throw new Error(`Could not find '${segment}' in '${resultIdentifier}'.`);
236 | }
237 | });
238 |
239 | if (result instanceof Function) {
240 | return result;
241 | } else {
242 | throw new Error(`The value '${resultIdentifier}' is not a function.`);
243 | }
244 | }
245 |
246 | class DotNetObject {
247 | constructor(private _id: number) {
248 | }
249 |
250 | public invokeMethod(methodIdentifier: string, ...args: any[]): T {
251 | return invokePossibleInstanceMethod(null, methodIdentifier, this._id, args);
252 | }
253 |
254 | public invokeMethodAsync(methodIdentifier: string, ...args: any[]): Promise {
255 | return invokePossibleInstanceMethodAsync(null, methodIdentifier, this._id, args);
256 | }
257 |
258 | public dispose() {
259 | const promise = invokeMethodAsync(
260 | 'Microsoft.JSInterop',
261 | 'DotNetDispatcher.ReleaseDotNetObject',
262 | this._id);
263 | promise.catch(error => console.error(error));
264 | }
265 |
266 | public serializeAsArg() {
267 | return `__dotNetObject:${this._id}`;
268 | }
269 | }
270 |
271 | const dotNetObjectValueFormat = /^__dotNetObject\:(\d+)$/;
272 | attachReviver(function reviveDotNetObject(key: any, value: any) {
273 | if (typeof value === 'string') {
274 | const match = value.match(dotNetObjectValueFormat);
275 | if (match) {
276 | return new DotNetObject(parseInt(match[1]));
277 | }
278 | }
279 |
280 | // Unrecognized - let another reviver handle it
281 | return value;
282 | });
283 |
284 | function argReplacer(key: string, value: any) {
285 | return value instanceof DotNetObject ? value.serializeAsArg() : value;
286 | }
287 | }
288 |
--------------------------------------------------------------------------------
/src/Microsoft.JSInterop.JS/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "noEmitOnError": true,
5 | "removeComments": false,
6 | "sourceMap": true,
7 | "target": "es5",
8 | "lib": ["es2015", "dom", "es2015.promise"],
9 | "strict": true,
10 | "declaration": true,
11 | "outDir": "dist"
12 | },
13 | "include": [
14 | "src/**/*.ts"
15 | ],
16 | "exclude": [
17 | "dist/**"
18 | ]
19 | }
20 |
--------------------------------------------------------------------------------
/src/Microsoft.JSInterop/DotNetDispatcher.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) .NET Foundation. All rights reserved.
2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3 |
4 | using Microsoft.JSInterop.Internal;
5 | using System;
6 | using System.Collections.Concurrent;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Reflection;
10 | using System.Threading.Tasks;
11 |
12 | namespace Microsoft.JSInterop
13 | {
14 | ///
15 | /// Provides methods that receive incoming calls from JS to .NET.
16 | ///
17 | public static class DotNetDispatcher
18 | {
19 | private static ConcurrentDictionary> _cachedMethodsByAssembly
20 | = new ConcurrentDictionary>();
21 |
22 | ///
23 | /// Receives a call from JS to .NET, locating and invoking the specified method.
24 | ///
25 | /// The assembly containing the method to be invoked.
26 | /// The identifier of the method to be invoked. The method must be annotated with a matching this identifier string.
27 | /// For instance method calls, identifies the target object.
28 | /// A JSON representation of the parameters.
29 | /// A JSON representation of the return value, or null.
30 | public static string Invoke(string assemblyName, string methodIdentifier, long dotNetObjectId, string argsJson)
31 | {
32 | // This method doesn't need [JSInvokable] because the platform is responsible for having
33 | // some way to dispatch calls here. The logic inside here is the thing that checks whether
34 | // the targeted method has [JSInvokable]. It is not itself subject to that restriction,
35 | // because there would be nobody to police that. This method *is* the police.
36 |
37 | // DotNetDispatcher only works with JSRuntimeBase instances.
38 | var jsRuntime = (JSRuntimeBase)JSRuntime.Current;
39 |
40 | var targetInstance = (object)null;
41 | if (dotNetObjectId != default)
42 | {
43 | targetInstance = jsRuntime.ArgSerializerStrategy.FindDotNetObject(dotNetObjectId);
44 | }
45 |
46 | var syncResult = InvokeSynchronously(assemblyName, methodIdentifier, targetInstance, argsJson);
47 | return syncResult == null ? null : Json.Serialize(syncResult, jsRuntime.ArgSerializerStrategy);
48 | }
49 |
50 | ///
51 | /// Receives a call from JS to .NET, locating and invoking the specified method asynchronously.
52 | ///
53 | /// A value identifying the asynchronous call that should be passed back with the result, or null if no result notification is required.
54 | /// The assembly containing the method to be invoked.
55 | /// The identifier of the method to be invoked. The method must be annotated with a matching this identifier string.
56 | /// For instance method calls, identifies the target object.
57 | /// A JSON representation of the parameters.
58 | /// A JSON representation of the return value, or null.
59 | public static void BeginInvoke(string callId, string assemblyName, string methodIdentifier, long dotNetObjectId, string argsJson)
60 | {
61 | // This method doesn't need [JSInvokable] because the platform is responsible for having
62 | // some way to dispatch calls here. The logic inside here is the thing that checks whether
63 | // the targeted method has [JSInvokable]. It is not itself subject to that restriction,
64 | // because there would be nobody to police that. This method *is* the police.
65 |
66 | // DotNetDispatcher only works with JSRuntimeBase instances.
67 | // If the developer wants to use a totally custom IJSRuntime, then their JS-side
68 | // code has to implement its own way of returning async results.
69 | var jsRuntimeBaseInstance = (JSRuntimeBase)JSRuntime.Current;
70 |
71 | var targetInstance = dotNetObjectId == default
72 | ? null
73 | : jsRuntimeBaseInstance.ArgSerializerStrategy.FindDotNetObject(dotNetObjectId);
74 |
75 | object syncResult = null;
76 | Exception syncException = null;
77 |
78 | try
79 | {
80 | syncResult = InvokeSynchronously(assemblyName, methodIdentifier, targetInstance, argsJson);
81 | }
82 | catch (Exception ex)
83 | {
84 | syncException = ex;
85 | }
86 |
87 | // If there was no callId, the caller does not want to be notified about the result
88 | if (callId != null)
89 | {
90 | // Invoke and coerce the result to a Task so the caller can use the same async API
91 | // for both synchronous and asynchronous methods
92 | var task = CoerceToTask(syncResult, syncException);
93 |
94 | task.ContinueWith(completedTask =>
95 | {
96 | try
97 | {
98 | var result = TaskGenericsUtil.GetTaskResult(completedTask);
99 | jsRuntimeBaseInstance.EndInvokeDotNet(callId, true, result);
100 | }
101 | catch (Exception ex)
102 | {
103 | ex = UnwrapException(ex);
104 | jsRuntimeBaseInstance.EndInvokeDotNet(callId, false, ex);
105 | }
106 | });
107 | }
108 | }
109 |
110 | private static Task CoerceToTask(object syncResult, Exception syncException)
111 | {
112 | if (syncException != null)
113 | {
114 | return Task.FromException(syncException);
115 | }
116 | else if (syncResult is Task syncResultTask)
117 | {
118 | return syncResultTask;
119 | }
120 | else
121 | {
122 | return Task.FromResult(syncResult);
123 | }
124 | }
125 |
126 | private static object InvokeSynchronously(string assemblyName, string methodIdentifier, object targetInstance, string argsJson)
127 | {
128 | if (targetInstance != null)
129 | {
130 | if (assemblyName != null)
131 | {
132 | throw new ArgumentException($"For instance method calls, '{nameof(assemblyName)}' should be null. Value received: '{assemblyName}'.");
133 | }
134 |
135 | assemblyName = targetInstance.GetType().Assembly.GetName().Name;
136 | }
137 |
138 | var (methodInfo, parameterTypes) = GetCachedMethodInfo(assemblyName, methodIdentifier);
139 |
140 | // There's no direct way to say we want to deserialize as an array with heterogenous
141 | // entry types (e.g., [string, int, bool]), so we need to deserialize in two phases.
142 | // First we deserialize as object[], for which SimpleJson will supply JsonObject
143 | // instances for nonprimitive values.
144 | var suppliedArgs = (object[])null;
145 | var suppliedArgsLength = 0;
146 | if (argsJson != null)
147 | {
148 | suppliedArgs = Json.Deserialize(argsJson).ToArray