@cloudbase/container 2.5.40-beta.0 → 2.5.41-beta.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.
@@ -15,15 +15,36 @@ export function isBuffer(buf: any) {
15
15
  return buf instanceof ArrayBuffer || ArrayBuffer.isView(buf)
16
16
  }
17
17
 
18
- export function serializeRequestBody<T>(headers, data: T): T | string {
18
+ function object2Qs(data) {
19
+ const list = Object.entries(data || {}).reduce((list, [key, value]: [string, string]) => {
20
+ list.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
21
+ return list
22
+ }, [])
23
+ if (list.length) {
24
+ return list.join('&')
25
+ }
26
+ }
27
+
28
+ export function serializeRequestBody<T>(headers, data: T, method = 'POST'): T | string {
19
29
  let res: T | string = data
20
- const contentType_key = 'Content-Type'
30
+ const contentTypeKey = 'Content-Type'
21
31
  if (typeof data === 'object' && !isBuffer(data)) {
22
- if (!headers[contentType_key] && !headers['content-type']) {
23
- headers[contentType_key] = 'application/json'
32
+ if (!headers[contentTypeKey] && !headers['content-type']) {
33
+ headers[contentTypeKey] = 'application/json'
24
34
  }
25
35
 
26
- const contentType = headers[contentType_key] || headers['content-type']
36
+ const contentType = headers[contentTypeKey] || headers['content-type']
37
+
38
+ if (method === 'GET') {
39
+ try {
40
+ return object2Qs(data) || ''
41
+ } catch (e) {
42
+ throw new Error(JSON.stringify({
43
+ code: ERRORS.INVALID_PARAMS,
44
+ msg: `[${COMPONENT_NAME}.callContainer] invalid data in query method, ${e.message}`,
45
+ }),)
46
+ }
47
+ }
27
48
 
28
49
  switch (contentType) {
29
50
  case 'application/json': {
@@ -39,12 +60,9 @@ export function serializeRequestBody<T>(headers, data: T): T | string {
39
60
  }
40
61
  case 'application/x-www-form-urlencoded': {
41
62
  try {
42
- const list = Object.entries(data || {}).reduce((list, [key, value]: [string, string]) => {
43
- list.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
44
- return list
45
- }, [])
46
- if (list.length) {
47
- res = list.join('&')
63
+ const qs = object2Qs(data)
64
+ if (qs) {
65
+ res = qs
48
66
  }
49
67
  } catch (e) {
50
68
  throw new Error(JSON.stringify({
@@ -0,0 +1,139 @@
1
+ // import decompress from 'brotli/decompress'
2
+ import Go from '../go_wams_exec'
3
+ import { parseURL } from '.'
4
+
5
+ async function instantiateStreaming(resp, importObject, brotliCompressed = false) {
6
+ if (brotliCompressed || !WebAssembly.instantiateStreaming) {
7
+ const source = await (await resp).arrayBuffer()
8
+ if (brotliCompressed) {
9
+ throw new Error('do not support *.br')
10
+ }
11
+ // const buffer = brotliCompressed ? decompress(new Int8Array(source)) : source
12
+ const buffer = source
13
+ return WebAssembly.instantiate(buffer, importObject)
14
+ }
15
+
16
+ return WebAssembly.instantiateStreaming(resp, importObject)
17
+ }
18
+
19
+ function isBrotliCompressed(url) {
20
+ let brotliCompressed = false
21
+
22
+ let pathname = ''
23
+ try {
24
+ const location = parseURL(url)
25
+ pathname = location.pathname
26
+ } catch (e) {
27
+ pathname = url
28
+ }
29
+
30
+ if (/\.br$/.test(pathname)) {
31
+ brotliCompressed = true
32
+ }
33
+ return brotliCompressed
34
+ }
35
+
36
+ export async function getExportFunction(url, module, mode = 'go') {
37
+ let importObject = {
38
+ env: {
39
+ memoryBase: 0,
40
+ tableBase: 0,
41
+ memory: new WebAssembly.Memory({
42
+ initial: 256,
43
+ }),
44
+ // table: new WebAssembly.Table({
45
+ // initial: 2,
46
+ // element: 'anyfunc',
47
+ // }),
48
+ },
49
+ ...module,
50
+ }
51
+ let go
52
+ const brotliCompressed = isBrotliCompressed(url)
53
+
54
+ if (mode === 'go') {
55
+ go = new Go()
56
+ go._initedModulePromise = new Promise((resolve) => {
57
+ go._initedModuleResolve = resolve
58
+ })
59
+ importObject = {
60
+ ...go.importObject,
61
+ env: {
62
+ ...go.importObject.env,
63
+ exportModule(module) {
64
+ return go._initedModuleResolve(module)
65
+ },
66
+ },
67
+ }
68
+ }
69
+
70
+ const reuslt = await instantiateStreaming(fetch(url), importObject, brotliCompressed)
71
+
72
+ if (mode === 'go') {
73
+ await Promise.race([
74
+ go.run(reuslt.instance),
75
+ new Promise(resolve => setTimeout(() => {
76
+ resolve(null)
77
+ }, 500),),
78
+ ])
79
+
80
+ return {
81
+ callContainer: (window as any).callContainer,
82
+ initContainer: (window as any).initContainer,
83
+ }
84
+ }
85
+
86
+ // if (mode === 'go') {
87
+ // go.run(reuslt.instance)
88
+ // const module = await go._initedModulePromise
89
+ // return module
90
+ // }
91
+
92
+ return reuslt.instance.exports
93
+ }
94
+
95
+ export async function loadJSExportFunction(config?: { vm: string; vender?: string }) {
96
+ const { vm, vender } = config || {}
97
+ const VENDER_KEY = 'cloudbase_private_link_vender'
98
+
99
+ if (vender || !Object.prototype.hasOwnProperty.call(document.defaultView, VENDER_KEY)) {
100
+ await loadUmdModule(
101
+ vender
102
+ || 'https://qbase.cdn-go.cn/lcap/lcap-resource-cdngo/-/release/_npm/@cloudbase/privatelink-vender@0.0.2/dist/cdn/cloudbase.privatelink.vender.js',
103
+ VENDER_KEY,
104
+ )
105
+ }
106
+
107
+ return loadUmdModule(
108
+ vm
109
+ || 'https://qbase.cdn-go.cn/lcap/lcap-resource-cdngo/-/release/_npm/@cloudbase/privatelink@0.0.1/dist/cdn/cloudbase.privatelink.vm.js',
110
+ 'cloudbase_private_link',
111
+ )
112
+ }
113
+
114
+ function loadUmdModule(jsUrl: string, umdModuleName: string, targetDoc: Document = document) {
115
+ return new Promise<any>((resolve, reject) => {
116
+ const win = targetDoc.defaultView
117
+
118
+ const script = targetDoc.createElement('script')
119
+ script.setAttribute('src', jsUrl)
120
+ script.setAttribute('class', umdModuleName)
121
+ script.addEventListener('load', () => {
122
+ if (Object.prototype.hasOwnProperty.call(win, umdModuleName)) {
123
+ return resolve(win[umdModuleName as any])
124
+ }
125
+ const error = new Error(`Fail to load UMD module ${umdModuleName} from [${jsUrl}].`)
126
+ return reject(error)
127
+ })
128
+
129
+ script.addEventListener('error', (e) => {
130
+ const error = new Error(`main bundle [${umdModuleName}] load failed from [${jsUrl}]: ${e?.message || ''}`)
131
+ reject(error)
132
+ })
133
+ if (targetDoc.body) {
134
+ targetDoc.body.appendChild(script)
135
+ } else {
136
+ targetDoc.head.appendChild(script)
137
+ }
138
+ })
139
+ }
@@ -0,0 +1,84 @@
1
+ const webpack = require('webpack')
2
+ const TerserPlugin = require('terser-webpack-plugin')
3
+ const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
4
+
5
+ module.exports = function (options) {
6
+ const { context, entry, output, mode, watch, externals, definePlugin = {}, optimization = {} } = options
7
+ const isDevelopment = mode !== 'production'
8
+ let plugins = [
9
+ // new WatchRunPlugin()
10
+ new webpack.DefinePlugin(
11
+ Object.assign(
12
+ {
13
+ 'globalThis.IS_MP_BUILD': false,
14
+ },
15
+ definePlugin,
16
+ ),
17
+ ),
18
+ // new BundleAnalyzerPlugin(),
19
+ ].filter((item) => !!item)
20
+ return {
21
+ context,
22
+ entry,
23
+ mode,
24
+ watch,
25
+ watchOptions: {
26
+ ignored: [output.path],
27
+ },
28
+ output,
29
+ externals,
30
+ cache: {
31
+ type: 'memory',
32
+ },
33
+ devtool: false,
34
+ resolve: {
35
+ extensions: ['.ts', '.js', '.json'],
36
+ },
37
+ module: {
38
+ rules: [
39
+ {
40
+ test: /\.ts$/,
41
+ exclude: [/node_modules/],
42
+ use: ['babel-loader', 'ts-loader'],
43
+ },
44
+ {
45
+ test: /\.js$/,
46
+ exclude: [/node_modules/],
47
+ use: ['babel-loader'],
48
+ },
49
+ {
50
+ test: /package\.json$/,
51
+ loader: 'package-json-cleanup-loader',
52
+ options: {
53
+ only: ['version'],
54
+ },
55
+ },
56
+ ],
57
+ noParse: [/sjcl\.js$/],
58
+ },
59
+ plugins,
60
+ optimization: {
61
+ moduleIds: 'deterministic',
62
+ emitOnErrors: false,
63
+ removeEmptyChunks: true,
64
+ usedExports: true,
65
+ splitChunks: false,
66
+ ...optimization,
67
+ ...(isDevelopment
68
+ ? {
69
+ minimize: false,
70
+ removeAvailableModules: false,
71
+ concatenateModules: true,
72
+ }
73
+ : {
74
+ minimizer: [
75
+ new TerserPlugin({
76
+ test: /\.js(\?.*)?$/i,
77
+ cache: false,
78
+ parallel: true,
79
+ }),
80
+ ],
81
+ }),
82
+ },
83
+ }
84
+ }
@@ -0,0 +1,22 @@
1
+ const path = require('path')
2
+
3
+ const params = {
4
+ context: path.resolve(__dirname, '../../'),
5
+ mode: 'production',
6
+ watch: false,
7
+ entry: path.resolve(__dirname, '../src/index.ts'),
8
+ output: {
9
+ path: path.resolve(__dirname, '../dist/miniprogram'),
10
+ filename: 'index.js',
11
+ library: `cloudbase_container`,
12
+ libraryTarget: 'umd',
13
+ umdNamedDefine: true,
14
+ globalObject: 'typeof window !== "undefined"?window:this',
15
+ },
16
+ externals: {},
17
+ definePlugin: {
18
+ 'globalThis.IS_MP_BUILD': true, // 注入环境变量,用于业务代码判断
19
+ },
20
+ }
21
+
22
+ module.exports = require('./web.prod.js')(params)