vite-plugin-cross-origin-storage 1.0.0
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/LICENSE +201 -0
- package/README.md +67 -0
- package/index.ts +202 -0
- package/loader.js +94 -0
- package/package.json +17 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# vite-plugin-cross-origin-storage
|
|
2
|
+
|
|
3
|
+
A Vite plugin to cache and load static assets (chunks) using the [Cross-Origin Storage (COS) API](https://github.com/WICG/cross-origin-storage).
|
|
4
|
+
|
|
5
|
+
This plugin progressively enhances your application by attempting to load vendor chunks and other assets from a shared Cross-Origin Storage, reducing bandwidth usage and improving load times across different sites that share common dependencies.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Automatic Import Rewriting**: Rewrites static imports to use COS-loaded Blob URLs when available.
|
|
10
|
+
- **Network Fallback**: Gracefully falls back to standard network requests if COS is unavailable or the asset is missing.
|
|
11
|
+
- **Smart Caching**: Automatically stores fetched assets into COS for future use.
|
|
12
|
+
- **Configurable**: Easily include or exclude specific chunks using glob patterns.
|
|
13
|
+
- **Runtime Loader**: Injects a lightweight loader to handle COS interactions transparently.
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install vite-plugin-cross-origin-storage --save-dev
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
Add the plugin to your `vite.config.ts` (or `vite.config.js`):
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { defineConfig } from 'vite';
|
|
27
|
+
import cosPlugin from 'vite-plugin-cross-origin-storage';
|
|
28
|
+
|
|
29
|
+
export default defineConfig({
|
|
30
|
+
plugins: [
|
|
31
|
+
cosPlugin({
|
|
32
|
+
// Configuration options
|
|
33
|
+
include: ['**/vendor-*'], // Example: only manage vendor chunks
|
|
34
|
+
}),
|
|
35
|
+
],
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Configuration
|
|
40
|
+
|
|
41
|
+
| Option | Type | Default | Description |
|
|
42
|
+
| :--- | :--- | :--- | :--- |
|
|
43
|
+
| `include` | `string \| RegExp \| Array` | `['**/*']` | Pattern to include chunks to be managed by COS. |
|
|
44
|
+
| `exclude` | `string \| RegExp \| Array` | `undefined` | Pattern to exclude chunks from being managed. |
|
|
45
|
+
|
|
46
|
+
## How It Works
|
|
47
|
+
|
|
48
|
+
1. **Build Time**:
|
|
49
|
+
- The plugin analyzes your bundle and identifies chunks matching the `include` pattern.
|
|
50
|
+
- It generates a stable hash for each managed chunk.
|
|
51
|
+
- It rewrites imports in your code to look for a global variable (e.g., `window.__COS_CHUNK_...`) containing the Blob URL of the chunk, falling back to the relative network path if the variable is unset.
|
|
52
|
+
- It disables the default `<script type="module" src="...">` entry point in your `index.html` and injects a custom `loader.js`.
|
|
53
|
+
|
|
54
|
+
2. **Runtime**:
|
|
55
|
+
- The injected loader checks for `navigator.crossOriginStorage`.
|
|
56
|
+
- If supported, it requests the file handle for each managed chunk using its hash.
|
|
57
|
+
- **Cache Hit**: If found, it creates a Blob URL and assigns it to the corresponding global variable.
|
|
58
|
+
- **Cache Miss**: If not found, it fetches the file from the network, stores it in COS, and then creates the Blob URL.
|
|
59
|
+
- Finally, the loader imports your application's entry point, which now seamlessly uses the cached assets.
|
|
60
|
+
|
|
61
|
+
## Requirements
|
|
62
|
+
|
|
63
|
+
- A browser with `Cross-Origin Storage` support (or a [browser extension](https://chromewebstore.google.com/detail/cross-origin-storage/denpnpcgjgikjpoglpjefakmdcbmlgih)).
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
Apache 2.0
|
package/index.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
import crypto from 'crypto';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import fs from 'fs';
|
|
5
|
+
import { fileURLToPath } from 'url';
|
|
6
|
+
import { createFilter } from '@rollup/pluginutils';
|
|
7
|
+
|
|
8
|
+
export interface CosPluginOptions {
|
|
9
|
+
/**
|
|
10
|
+
* Pattern to include chunks to be managed by COS.
|
|
11
|
+
* Matches against the output filename (e.g. `assets/vendor-*.js`).
|
|
12
|
+
* Default: `['**\/*']` (all chunks, except the entry implementation detail)
|
|
13
|
+
*/
|
|
14
|
+
include?: string | RegExp | (string | RegExp)[];
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Pattern to exclude chunks from being managed by COS.
|
|
18
|
+
*/
|
|
19
|
+
exclude?: string | RegExp | (string | RegExp)[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export default function cosPlugin(options: CosPluginOptions = {}): Plugin {
|
|
23
|
+
const filter = createFilter(options.include || ['**/*'], options.exclude);
|
|
24
|
+
|
|
25
|
+
// Resolve loader path relative to this file
|
|
26
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
27
|
+
const loaderPath = path.resolve(__dirname, 'loader.js');
|
|
28
|
+
|
|
29
|
+
return {
|
|
30
|
+
name: 'vite-plugin-cos',
|
|
31
|
+
apply: 'build',
|
|
32
|
+
enforce: 'post',
|
|
33
|
+
|
|
34
|
+
transformIndexHtml: {
|
|
35
|
+
order: 'post',
|
|
36
|
+
handler(html) {
|
|
37
|
+
// Disable standard entry script to let the COS loader handle it
|
|
38
|
+
return html.replace(
|
|
39
|
+
/<script\s+[^>]*type=["']module["'][^>]*src=["'][^"']*index[^"']*["'][^>]*><\/script>/gi,
|
|
40
|
+
'<!-- Entry script disabled by COS Plugin -->'
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
async generateBundle(_options, bundle) {
|
|
46
|
+
const managedChunks: Record<string, any> = {};
|
|
47
|
+
let mainChunk: any = null;
|
|
48
|
+
let htmlAsset: any = null;
|
|
49
|
+
|
|
50
|
+
for (const fileName in bundle) {
|
|
51
|
+
const chunk = bundle[fileName];
|
|
52
|
+
if (chunk.type === 'chunk') {
|
|
53
|
+
if (chunk.isEntry) {
|
|
54
|
+
mainChunk = chunk;
|
|
55
|
+
} else {
|
|
56
|
+
// Apply filter to determine if this chunk should be managed by COS
|
|
57
|
+
if (filter(fileName)) {
|
|
58
|
+
managedChunks[fileName] = chunk;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (fileName === 'index.html' && chunk.type === 'asset') {
|
|
63
|
+
htmlAsset = chunk;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (mainChunk) {
|
|
68
|
+
// Step 1: Assign stable global variables to managed chunks
|
|
69
|
+
// We do this BEFORE calculating hashes because the global variable names
|
|
70
|
+
// are needed for import rewriting, which changes the code, which changes the hash.
|
|
71
|
+
const chunkInfo: Record<string, { globalVar: string, chunk: any }> = {};
|
|
72
|
+
|
|
73
|
+
for (const fileName in managedChunks) {
|
|
74
|
+
// We use a hash of the filename to ensure it's a valid JS identifier and relatively short
|
|
75
|
+
// detailed: using filename hash creates a stable identifier for the lifetime of the file path
|
|
76
|
+
const nameHash = crypto.createHash('sha256').update(fileName).digest('hex').substring(0, 8);
|
|
77
|
+
chunkInfo[fileName] = {
|
|
78
|
+
globalVar: `__COS_CHUNK_${nameHash}__`,
|
|
79
|
+
chunk: managedChunks[fileName]
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Collect ALL chunks to rewrite imports in them
|
|
84
|
+
const allChunks = Object.values(bundle).filter(c => c.type === 'chunk');
|
|
85
|
+
|
|
86
|
+
// Step 2: Rewrite imports TO managed chunks in ALL chunks
|
|
87
|
+
// This modifies the importers to look for the global variable (Blob URL)
|
|
88
|
+
for (const targetChunk of allChunks) {
|
|
89
|
+
for (const fileName in chunkInfo) {
|
|
90
|
+
// Avoid self-reference
|
|
91
|
+
if (targetChunk.fileName === fileName) continue;
|
|
92
|
+
|
|
93
|
+
const { globalVar } = chunkInfo[fileName];
|
|
94
|
+
const chunkBasename = fileName.split('/').pop()!;
|
|
95
|
+
const escapedName = chunkBasename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
96
|
+
// Regex to find static imports of the managed chunk
|
|
97
|
+
const pattern = `import\\s*\\{([^}]+)\\}\\s*from\\s*['"]\\.\\/${escapedName}['"];?`;
|
|
98
|
+
const importRegex = new RegExp(pattern, 'g');
|
|
99
|
+
|
|
100
|
+
if (importRegex.test(targetChunk.code)) {
|
|
101
|
+
// Calculate relative path for fallback (in case COS loading fails or is unavailable)
|
|
102
|
+
// targetChunk.fileName is the importer (e.g. "assets/index.js")
|
|
103
|
+
// fileName is the importee (e.g. "assets/vendor.js")
|
|
104
|
+
// We need "./vendor.js", not "./assets/vendor.js"
|
|
105
|
+
let relativePath = path.relative(path.dirname(targetChunk.fileName), fileName);
|
|
106
|
+
if (!relativePath.startsWith('.')) {
|
|
107
|
+
relativePath = `./${relativePath}`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
targetChunk.code = targetChunk.code.replace(importRegex, (_match: string, bindings: string) => {
|
|
111
|
+
const destructuringPattern = bindings.split(',').map(b => {
|
|
112
|
+
const parts = b.trim().split(/\s+as\s+/);
|
|
113
|
+
return parts.length === 2 ? `${parts[0]}:${parts[1]}` : parts[0];
|
|
114
|
+
}).join(',');
|
|
115
|
+
return `const {${destructuringPattern}}=await import(window.${globalVar}||"${relativePath}");`;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Step 3: Rewrite imports to UNMANAGED chunks in MANAGED chunks.
|
|
122
|
+
// Managed chunks are loaded via Blob URLs. Relative imports fail in Blob URLs.
|
|
123
|
+
// Absolute paths (e.g. "/assets/foo.js") work but depend on the app being at domain root.
|
|
124
|
+
// To support subdirectories (and typical "base: './'" configs), we usage dynamic imports
|
|
125
|
+
// with runtime URL resolution against `document.baseURI`.
|
|
126
|
+
for (const fileName in managedChunks) {
|
|
127
|
+
const chunk = managedChunks[fileName];
|
|
128
|
+
// Check all imports designated by Rollup
|
|
129
|
+
chunk.imports.forEach((importedFile: string) => {
|
|
130
|
+
// If the importedFile is NOT in chunkInfo, it is unmanaged.
|
|
131
|
+
if (!chunkInfo[importedFile]) {
|
|
132
|
+
const importedBasename = importedFile.split('/').pop()!;
|
|
133
|
+
const escapedName = importedBasename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
134
|
+
|
|
135
|
+
// We need to match the full import statement to rewrite it to a destructuring assignment
|
|
136
|
+
// Pattern: import { a as b, c } from "./foo.js";
|
|
137
|
+
const pattern = `import\\s*\\{([^}]+)\\}\\s*from\\s*['"]\\.\\/${escapedName}['"];?`;
|
|
138
|
+
const importRegex = new RegExp(pattern, 'g');
|
|
139
|
+
|
|
140
|
+
if (importRegex.test(chunk.code)) {
|
|
141
|
+
chunk.code = chunk.code.replace(importRegex, (_match: string, bindings: string) => {
|
|
142
|
+
const destructuringPattern = bindings.split(',').map(b => {
|
|
143
|
+
const parts = b.trim().split(/\s+as\s+/);
|
|
144
|
+
return parts.length === 2 ? `${parts[0]}:${parts[1]}` : parts[0];
|
|
145
|
+
}).join(',');
|
|
146
|
+
// Rewrite to dynamic import using document.baseURI to resolve the path correctly relative to the page
|
|
147
|
+
return `const {${destructuringPattern}}=await import(new URL("${importedFile}", document.baseURI).href);`;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Also handle side-effect imports if any? (Likely not for vendor chunks, but good to be safe?)
|
|
152
|
+
// For now, focusing on named imports as that's what Rollup outputs for code splitting.
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Step 4: Calculate final hashes and build manifest
|
|
158
|
+
// Now that code is modified (rewritten), we calculate the hash of the ACTUAL content that will be on disk.
|
|
159
|
+
// This ensures that if the rewrite logic changes (e.g. absolute paths), the hash changes, busting the COS cache.
|
|
160
|
+
const manifest: Record<string, any> = {};
|
|
161
|
+
for (const fileName in chunkInfo) {
|
|
162
|
+
const { chunk, globalVar } = chunkInfo[fileName];
|
|
163
|
+
const finalHash = crypto.createHash('sha256').update(chunk.code).digest('hex');
|
|
164
|
+
|
|
165
|
+
manifest[fileName] = {
|
|
166
|
+
file: `/${fileName}`,
|
|
167
|
+
hash: finalHash,
|
|
168
|
+
globalVar: globalVar
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
manifest['index'] = {
|
|
173
|
+
file: `/${mainChunk.fileName}`
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// Inject loader and inlined manifest into index.html
|
|
177
|
+
if (htmlAsset) {
|
|
178
|
+
try {
|
|
179
|
+
let loaderCode = fs.readFileSync(loaderPath, 'utf-8');
|
|
180
|
+
loaderCode = loaderCode.replace('__COS_MANIFEST__', JSON.stringify(manifest));
|
|
181
|
+
|
|
182
|
+
let htmlSource = htmlAsset.source as string;
|
|
183
|
+
|
|
184
|
+
// Remove modulepreload links to avoid double fetching keys we manage
|
|
185
|
+
htmlSource = htmlSource.replace(
|
|
186
|
+
/<link\s+[^>]*rel=["']modulepreload["'][^>]*>/gi,
|
|
187
|
+
'<!-- modulepreload disabled by COS Plugin -->'
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
// Inject into head
|
|
191
|
+
htmlAsset.source = htmlSource.replace(
|
|
192
|
+
'<head>',
|
|
193
|
+
() => `<head>\n<script id="cos-loader">${loaderCode}</script>`
|
|
194
|
+
);
|
|
195
|
+
} catch (e) {
|
|
196
|
+
console.error('COS Plugin: Failed to read loader.js', e);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
}
|
package/loader.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
(async function () {
|
|
2
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
3
|
+
|
|
4
|
+
const isCOSAvailable = 'crossOriginStorage' in navigator;
|
|
5
|
+
console.log('COS Loader: isCOSAvailable =', isCOSAvailable);
|
|
6
|
+
|
|
7
|
+
// Manifest is injected by the Vite plugin
|
|
8
|
+
// @ts-ignore
|
|
9
|
+
const manifest = __COS_MANIFEST__;
|
|
10
|
+
|
|
11
|
+
const mainEntry = manifest && manifest['index'];
|
|
12
|
+
if (!mainEntry) {
|
|
13
|
+
console.warn('COS Loader: Missing main entry in manifest.');
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Identify managed chunks (anything with a hash)
|
|
18
|
+
const chunksToLoad = Object.values(manifest).filter(item => item.hash);
|
|
19
|
+
|
|
20
|
+
async function getBlobFromCOS(hash) {
|
|
21
|
+
if (!isCOSAvailable) return null;
|
|
22
|
+
try {
|
|
23
|
+
const handles = await navigator.crossOriginStorage.requestFileHandles([
|
|
24
|
+
{ algorithm: 'SHA-256', value: hash },
|
|
25
|
+
]);
|
|
26
|
+
if (handles && handles.length > 0) {
|
|
27
|
+
return await handles[0].getFile();
|
|
28
|
+
}
|
|
29
|
+
} catch (err) {
|
|
30
|
+
if (err.name !== 'NotFoundError') console.error('COS Loader: Error checking COS', err);
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function storeBlobInCOS(blob, hash) {
|
|
36
|
+
if (!isCOSAvailable) return;
|
|
37
|
+
try {
|
|
38
|
+
const handles = await navigator.crossOriginStorage.requestFileHandles(
|
|
39
|
+
[{ algorithm: 'SHA-256', value: hash }],
|
|
40
|
+
{ create: true }
|
|
41
|
+
);
|
|
42
|
+
if (handles && handles.length > 0) {
|
|
43
|
+
const writable = await handles[0].createWritable();
|
|
44
|
+
await writable.write(blob);
|
|
45
|
+
await writable.close();
|
|
46
|
+
console.log('COS Loader: Stored bundle in COS', hash);
|
|
47
|
+
}
|
|
48
|
+
} catch (err) {
|
|
49
|
+
console.error('COS Loader: Failed to store in COS', err);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Load all managed chunks in parallel
|
|
54
|
+
// If COS is not available, we skip this and fall back to native network loading via the import() rewrites.
|
|
55
|
+
if (isCOSAvailable && chunksToLoad.length > 0) {
|
|
56
|
+
await Promise.all(chunksToLoad.map(async (chunk) => {
|
|
57
|
+
let url = null;
|
|
58
|
+
|
|
59
|
+
const cosBlob = await getBlobFromCOS(chunk.hash);
|
|
60
|
+
if (cosBlob) {
|
|
61
|
+
console.log(`COS Loader: Loaded ${chunk.file} from COS!`);
|
|
62
|
+
url = URL.createObjectURL(new Blob([cosBlob], { type: 'application/javascript' }));
|
|
63
|
+
} else {
|
|
64
|
+
console.log(`COS Loader: ${chunk.file} not in COS, fetching...`);
|
|
65
|
+
try {
|
|
66
|
+
const response = await fetch(chunk.file);
|
|
67
|
+
if (response.ok) {
|
|
68
|
+
const blob = await response.blob();
|
|
69
|
+
url = URL.createObjectURL(new Blob([blob], { type: 'application/javascript' }));
|
|
70
|
+
// Store in COS for next time
|
|
71
|
+
storeBlobInCOS(blob, chunk.hash);
|
|
72
|
+
} else {
|
|
73
|
+
console.error(`COS Loader: Fetch failed with status ${response.status}`);
|
|
74
|
+
}
|
|
75
|
+
} catch (e) {
|
|
76
|
+
console.error(`COS Loader: Network fetch failed for ${chunk.file}`, e);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Set global variable if we have a URL
|
|
81
|
+
if (url && chunk.globalVar) {
|
|
82
|
+
window[chunk.globalVar] = url;
|
|
83
|
+
}
|
|
84
|
+
}));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Start App
|
|
88
|
+
try {
|
|
89
|
+
console.log('COS Loader: Starting app...');
|
|
90
|
+
await import(mainEntry.file);
|
|
91
|
+
} catch (err) {
|
|
92
|
+
console.error('COS Loader: Failed to start app', err);
|
|
93
|
+
}
|
|
94
|
+
})();
|
package/package.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vite-plugin-cross-origin-storage",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Vite plugin to load chunks from Cross-Origin Storage",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"index.ts",
|
|
9
|
+
"loader.js"
|
|
10
|
+
],
|
|
11
|
+
"peerDependencies": {
|
|
12
|
+
"vite": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@rollup/pluginutils": "^5.3.0"
|
|
16
|
+
}
|
|
17
|
+
}
|