|
1 | 1 | import { defineHeadPlugin } from './defineHeadPlugin'
|
2 | 2 |
|
3 |
| -async function resolvePromisesRecursively(root: any): Promise<any> { |
4 |
| - if (root instanceof Promise) { |
5 |
| - return await root |
| 3 | +async function walkPromises(v: any): Promise<any> { |
| 4 | + const type = typeof v |
| 5 | + if (type === 'function') { |
| 6 | + return v |
6 | 7 | }
|
7 |
| - // could be a root primitive, array or object |
8 |
| - if (Array.isArray(root)) { |
9 |
| - return Promise.all(root.map(r => resolvePromisesRecursively(r))) |
| 8 | + // Combined primitive type check |
| 9 | + if (v instanceof Promise) { |
| 10 | + return await v |
10 | 11 | }
|
11 |
| - if (typeof root === 'object') { |
12 |
| - const resolved: Record<string, string> = {} |
13 | 12 |
|
14 |
| - for (const k in root) { |
15 |
| - if (!Object.hasOwn(root, k)) |
16 |
| - continue |
| 13 | + if (Array.isArray(v)) { |
| 14 | + return await Promise.all(v.map(r => walkPromises(r))) |
| 15 | + } |
17 | 16 |
|
18 |
| - resolved[k] = await resolvePromisesRecursively(root[k]) |
| 17 | + if (v?.constructor === Object) { |
| 18 | + const next: Record<string, any> = {} |
| 19 | + for (const key of Object.keys(v)) { |
| 20 | + next[key] = await walkPromises(v[key]) |
19 | 21 | }
|
20 |
| - |
21 |
| - return resolved |
| 22 | + return next |
22 | 23 | }
|
23 |
| - return root |
| 24 | + |
| 25 | + return v |
24 | 26 | }
|
25 | 27 |
|
26 | 28 | export const PromisesPlugin = /* @__PURE__ */ defineHeadPlugin({
|
27 | 29 | key: 'promises',
|
28 | 30 | hooks: {
|
29 | 31 | 'entries:resolve': async (ctx) => {
|
| 32 | + const promises = [] |
30 | 33 | for (const k in ctx.entries) {
|
31 |
| - ctx.entries[k].input = await resolvePromisesRecursively(ctx.entries[k].input) |
| 34 | + if (!ctx.entries[k]._promisesProcessed) { |
| 35 | + promises.push( |
| 36 | + walkPromises(ctx.entries[k].input).then((val) => { |
| 37 | + ctx.entries[k].input = val |
| 38 | + ctx.entries[k]._promisesProcessed = true |
| 39 | + }), |
| 40 | + ) |
| 41 | + } |
32 | 42 | }
|
| 43 | + await Promise.all(promises) |
33 | 44 | },
|
34 | 45 | },
|
35 | 46 | })
|
0 commit comments