@cfp-studio/plugin-react 17.3.7 → 17.3.9
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/dist/index.d.mts +22 -41
- package/dist/index.mjs +1 -1
- package/package.json +8 -7
- package/preview/index.tsx +13 -3
- package/preview/render-19.tsx +90 -0
- package/preview/shims/router-utils.spec.ts +0 -158
package/dist/index.d.mts
CHANGED
|
@@ -16,12 +16,11 @@ import * as stream from "node:stream";
|
|
|
16
16
|
import { Duplex, DuplexOptions } from "node:stream";
|
|
17
17
|
import { SecureContextOptions } from "node:tls";
|
|
18
18
|
import { ZlibOptions } from "node:zlib";
|
|
19
|
-
import Lightningcss from "lightningcss";
|
|
20
19
|
import SassEmbedded from "sass-embedded";
|
|
21
20
|
import Less from "less";
|
|
22
21
|
import Stylus from "stylus";
|
|
23
22
|
|
|
24
|
-
//#region ../../../../node_modules/.pnpm/@types+estree@1.0.
|
|
23
|
+
//#region ../../../../node_modules/.pnpm/@types+estree@1.0.8/node_modules/@types/estree/index.d.ts
|
|
25
24
|
// This definition file follows a somewhat unusual format. ESTree allows
|
|
26
25
|
// runtime type checks based on the `type` parameter. In order to explain this
|
|
27
26
|
// to typescript we want to use discriminated union types:
|
|
@@ -271,7 +270,7 @@ interface PrivateIdentifier extends BaseNode {
|
|
|
271
270
|
}
|
|
272
271
|
interface Property extends BaseNode {
|
|
273
272
|
type: "Property";
|
|
274
|
-
key: Expression;
|
|
273
|
+
key: Expression | PrivateIdentifier;
|
|
275
274
|
value: Expression | Pattern; // Could be an AssignmentProperty
|
|
276
275
|
kind: "init" | "get" | "set";
|
|
277
276
|
method: boolean;
|
|
@@ -545,7 +544,7 @@ interface AwaitExpression extends BaseExpression {
|
|
|
545
544
|
argument: Expression;
|
|
546
545
|
}
|
|
547
546
|
//#endregion
|
|
548
|
-
//#region ../../../../node_modules/.pnpm/rollup@4.
|
|
547
|
+
//#region ../../../../node_modules/.pnpm/rollup@4.52.0/node_modules/rollup/dist/rollup.d.ts
|
|
549
548
|
declare module 'estree' {
|
|
550
549
|
export interface Decorator extends BaseNode {
|
|
551
550
|
type: 'Decorator';
|
|
@@ -625,11 +624,11 @@ type DecodedSourceMapOrMissing = {
|
|
|
625
624
|
missing?: false | undefined;
|
|
626
625
|
});
|
|
627
626
|
interface SourceMap$1 {
|
|
628
|
-
file
|
|
627
|
+
file: string;
|
|
629
628
|
mappings: string;
|
|
630
629
|
names: string[];
|
|
631
630
|
sources: string[];
|
|
632
|
-
sourcesContent?:
|
|
631
|
+
sourcesContent?: string[] | undefined;
|
|
633
632
|
version: number;
|
|
634
633
|
debugId?: string | undefined;
|
|
635
634
|
toString(): string;
|
|
@@ -651,8 +650,7 @@ interface SourceDescription extends Partial<PartialNull<ModuleOptions>> {
|
|
|
651
650
|
}
|
|
652
651
|
interface TransformModuleJSON {
|
|
653
652
|
ast?: ProgramNode | undefined;
|
|
654
|
-
code: string;
|
|
655
|
-
safeVariableNames: Record<string, string> | null; // note if plugins use new this.cache to opt-out auto transform cache
|
|
653
|
+
code: string; // note if plugins use new this.cache to opt-out auto transform cache
|
|
656
654
|
customTransformCache: boolean;
|
|
657
655
|
originalCode: string;
|
|
658
656
|
originalSourcemap: ExistingDecodedSourceMap | null;
|
|
@@ -660,7 +658,6 @@ interface TransformModuleJSON {
|
|
|
660
658
|
transformDependencies: string[];
|
|
661
659
|
}
|
|
662
660
|
interface ModuleJSON extends TransformModuleJSON, ModuleOptions {
|
|
663
|
-
safeVariableNames: Record<string, string> | null;
|
|
664
661
|
ast: ProgramNode;
|
|
665
662
|
dependencies: string[];
|
|
666
663
|
id: string;
|
|
@@ -716,7 +713,6 @@ interface ModuleInfo extends ModuleOptions {
|
|
|
716
713
|
dynamicallyImportedIds: readonly string[];
|
|
717
714
|
exportedBindings: Record<string, string[]> | null;
|
|
718
715
|
exports: string[] | null;
|
|
719
|
-
safeVariableNames: Record<string, string> | null;
|
|
720
716
|
hasDefaultExport: boolean | null;
|
|
721
717
|
id: string;
|
|
722
718
|
implicitlyLoadedAfterOneOf: readonly string[];
|
|
@@ -764,7 +760,6 @@ interface PluginContext extends MinimalPluginContext$1 {
|
|
|
764
760
|
} & Partial<PartialNull<ModuleOptions>>) => Promise<ModuleInfo>;
|
|
765
761
|
parse: ParseAst;
|
|
766
762
|
resolve: (source: string, importer?: string, options?: {
|
|
767
|
-
importerAttributes?: Record<string, string>;
|
|
768
763
|
attributes?: Record<string, string>;
|
|
769
764
|
custom?: CustomPluginOptions;
|
|
770
765
|
isEntry?: boolean;
|
|
@@ -801,12 +796,10 @@ type ResolveIdResult = string | NullValue | false | PartialResolvedId;
|
|
|
801
796
|
type ResolveIdHook = (this: PluginContext, source: string, importer: string | undefined, options: {
|
|
802
797
|
attributes: Record<string, string>;
|
|
803
798
|
custom?: CustomPluginOptions;
|
|
804
|
-
importerAttributes?: Record<string, string> | undefined;
|
|
805
799
|
isEntry: boolean;
|
|
806
800
|
}) => ResolveIdResult;
|
|
807
801
|
type ShouldTransformCachedModuleHook = (this: PluginContext, options: {
|
|
808
802
|
ast: ProgramNode;
|
|
809
|
-
attributes: Record<string, string>;
|
|
810
803
|
code: string;
|
|
811
804
|
id: string;
|
|
812
805
|
meta: CustomPluginOptions;
|
|
@@ -817,12 +810,7 @@ type ShouldTransformCachedModuleHook = (this: PluginContext, options: {
|
|
|
817
810
|
type IsExternal = (source: string, importer: string | undefined, isResolved: boolean) => boolean;
|
|
818
811
|
type HasModuleSideEffects = (id: string, external: boolean) => boolean;
|
|
819
812
|
type LoadResult = SourceDescription | string | NullValue;
|
|
820
|
-
type LoadHook = (this: PluginContext, id: string
|
|
821
|
-
options?: {
|
|
822
|
-
// unused, temporarily added for better Vite type-compatibility
|
|
823
|
-
ssr?: boolean | undefined; // temporarily marked as optional for better Vite type-compatibility
|
|
824
|
-
attributes?: Record<string, string>;
|
|
825
|
-
} | undefined) => LoadResult;
|
|
813
|
+
type LoadHook = (this: PluginContext, id: string) => LoadResult;
|
|
826
814
|
interface TransformPluginContext extends PluginContext {
|
|
827
815
|
debug: LoggingFunctionWithPosition;
|
|
828
816
|
error: (error: RollupError | string, pos?: number | {
|
|
@@ -834,12 +822,7 @@ interface TransformPluginContext extends PluginContext {
|
|
|
834
822
|
warn: LoggingFunctionWithPosition;
|
|
835
823
|
}
|
|
836
824
|
type TransformResult$2 = string | NullValue | Partial<SourceDescription>;
|
|
837
|
-
type TransformHook = (this: TransformPluginContext, code: string, id: string
|
|
838
|
-
options?: {
|
|
839
|
-
// unused, temporarily added for better Vite type-compatibility
|
|
840
|
-
ssr?: boolean | undefined; // temporarily marked as optional for better Vite type-compatibility
|
|
841
|
-
attributes?: Record<string, string>;
|
|
842
|
-
} | undefined) => TransformResult$2;
|
|
825
|
+
type TransformHook = (this: TransformPluginContext, code: string, id: string) => TransformResult$2;
|
|
843
826
|
type ModuleParsedHook = (this: PluginContext, info: ModuleInfo) => void;
|
|
844
827
|
type RenderChunkHook = (this: PluginContext, code: string, chunk: RenderedChunk, options: NormalizedOutputOptions, meta: {
|
|
845
828
|
chunks: Record<string, RenderedChunk>;
|
|
@@ -849,16 +832,13 @@ type RenderChunkHook = (this: PluginContext, code: string, chunk: RenderedChunk,
|
|
|
849
832
|
} | string | NullValue;
|
|
850
833
|
type ResolveDynamicImportHook = (this: PluginContext, specifier: string | AstNode, importer: string, options: {
|
|
851
834
|
attributes: Record<string, string>;
|
|
852
|
-
importerAttributes: Record<string, string>;
|
|
853
835
|
}) => ResolveIdResult;
|
|
854
836
|
type ResolveImportMetaHook = (this: PluginContext, property: string | null, options: {
|
|
855
|
-
attributes: Record<string, string>;
|
|
856
837
|
chunkId: string;
|
|
857
838
|
format: InternalModuleFormat;
|
|
858
839
|
moduleId: string;
|
|
859
840
|
}) => string | NullValue;
|
|
860
841
|
type ResolveFileUrlHook = (this: PluginContext, options: {
|
|
861
|
-
attributes: Record<string, string>;
|
|
862
842
|
chunkId: string;
|
|
863
843
|
fileName: string;
|
|
864
844
|
format: InternalModuleFormat;
|
|
@@ -909,7 +889,6 @@ interface FunctionPluginHooks {
|
|
|
909
889
|
chunk: PreRenderedChunkWithFileName;
|
|
910
890
|
targetChunk: PreRenderedChunkWithFileName | null;
|
|
911
891
|
getTargetChunkImports: () => DynamicImportTargetChunk[] | null;
|
|
912
|
-
targetModuleAttributes: Record<string, string>;
|
|
913
892
|
}) => {
|
|
914
893
|
left: string;
|
|
915
894
|
right: string;
|
|
@@ -1325,14 +1304,16 @@ interface AwaitingEventEmitter<T extends Record<string, (...parameters: any) =>
|
|
|
1325
1304
|
off<K extends keyof T>(event: K, listener: AwaitedEventListener<T, K>): this;
|
|
1326
1305
|
/**
|
|
1327
1306
|
* Registers an event listener that will be awaited before Rollup continues.
|
|
1328
|
-
* All listeners
|
|
1329
|
-
*
|
|
1307
|
+
* All listeners will be awaited in parallel while rejections are tracked via
|
|
1308
|
+
* Promise.all.
|
|
1330
1309
|
*/
|
|
1331
1310
|
on<K extends keyof T>(event: K, listener: AwaitedEventListener<T, K>): this;
|
|
1332
1311
|
/**
|
|
1333
|
-
* Registers an event listener
|
|
1334
|
-
*
|
|
1335
|
-
*
|
|
1312
|
+
* Registers an event listener that will be awaited before Rollup continues.
|
|
1313
|
+
* All listeners will be awaited in parallel while rejections are tracked via
|
|
1314
|
+
* Promise.all.
|
|
1315
|
+
* Listeners are removed automatically when removeListenersForCurrentRun is
|
|
1316
|
+
* called, which happens automatically after each run.
|
|
1336
1317
|
*/
|
|
1337
1318
|
onCurrentRun<K extends keyof T>(event: K, listener: (...parameters: Parameters<T[K]>) => Promise<ReturnType<T[K]>>): this;
|
|
1338
1319
|
removeAllListeners(): this;
|
|
@@ -1433,7 +1414,7 @@ interface RollupFileStats {
|
|
|
1433
1414
|
birthtime: Date;
|
|
1434
1415
|
}
|
|
1435
1416
|
//#endregion
|
|
1436
|
-
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.
|
|
1417
|
+
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.19.2_jiti@2.7.0_less@4.9.1_lightningcss@1.30.2_sass@1.107.1_t_8ea963fdf6f230da68c5cacf71b7d6dc/node_modules/vite/types/hmrPayload.d.ts
|
|
1437
1418
|
type HotPayload = ConnectedPayload | PingPayload | UpdatePayload | FullReloadPayload | CustomPayload | ErrorPayload | PrunePayload;
|
|
1438
1419
|
interface ConnectedPayload {
|
|
1439
1420
|
type: 'connected';
|
|
@@ -1492,7 +1473,7 @@ interface ErrorPayload {
|
|
|
1492
1473
|
};
|
|
1493
1474
|
}
|
|
1494
1475
|
//#endregion
|
|
1495
|
-
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.
|
|
1476
|
+
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.19.2_jiti@2.7.0_less@4.9.1_lightningcss@1.30.2_sass@1.107.1_t_8ea963fdf6f230da68c5cacf71b7d6dc/node_modules/vite/types/customEvent.d.ts
|
|
1496
1477
|
interface CustomEventMap {
|
|
1497
1478
|
'vite:beforeUpdate': UpdatePayload;
|
|
1498
1479
|
'vite:afterUpdate': UpdatePayload;
|
|
@@ -1523,7 +1504,7 @@ interface InvalidatePayload {
|
|
|
1523
1504
|
*/
|
|
1524
1505
|
type InferCustomEventPayload<T extends string> = T extends keyof CustomEventMap ? CustomEventMap[T] : any;
|
|
1525
1506
|
//#endregion
|
|
1526
|
-
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.
|
|
1507
|
+
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.19.2_jiti@2.7.0_less@4.9.1_lightningcss@1.30.2_sass@1.107.1_t_8ea963fdf6f230da68c5cacf71b7d6dc/node_modules/vite/dist/node/moduleRunnerTransport.d-DJ_mE5sf.d.ts
|
|
1527
1508
|
interface FetchFunctionOptions {
|
|
1528
1509
|
cached?: boolean;
|
|
1529
1510
|
startOffset?: number;
|
|
@@ -2186,12 +2167,12 @@ declare global {
|
|
|
2186
2167
|
interface URL {}
|
|
2187
2168
|
}
|
|
2188
2169
|
//#endregion
|
|
2189
|
-
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.
|
|
2170
|
+
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.19.2_jiti@2.7.0_less@4.9.1_lightningcss@1.30.2_sass@1.107.1_t_8ea963fdf6f230da68c5cacf71b7d6dc/node_modules/vite/types/internal/lightningcssOptions.d.ts
|
|
2190
2171
|
/* eslint-enable @typescript-eslint/ban-ts-comment */
|
|
2191
2172
|
type LightningCSSOptions = Omit<Lightningcss.BundleAsyncOptions<Lightningcss.CustomAtRules>, 'filename' | 'resolver' | 'minify' | 'sourceMap' | 'analyzeDependencies' // properties not overridden by Vite, but does not make sense to set by end users
|
|
2192
2173
|
| 'inputSourceMap' | 'projectRoot'>;
|
|
2193
2174
|
//#endregion
|
|
2194
|
-
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.
|
|
2175
|
+
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.19.2_jiti@2.7.0_less@4.9.1_lightningcss@1.30.2_sass@1.107.1_t_8ea963fdf6f230da68c5cacf71b7d6dc/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts
|
|
2195
2176
|
/* eslint-enable @typescript-eslint/ban-ts-comment */
|
|
2196
2177
|
// https://github.com/type-challenges/type-challenges/issues/29285
|
|
2197
2178
|
type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false;
|
|
@@ -2214,7 +2195,7 @@ declare global {
|
|
|
2214
2195
|
interface HTMLLinkElement {}
|
|
2215
2196
|
}
|
|
2216
2197
|
//#endregion
|
|
2217
|
-
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.
|
|
2198
|
+
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.19.2_jiti@2.7.0_less@4.9.1_lightningcss@1.30.2_sass@1.107.1_t_8ea963fdf6f230da68c5cacf71b7d6dc/node_modules/vite/types/metadata.d.ts
|
|
2218
2199
|
interface ChunkMetadata {
|
|
2219
2200
|
importedAssets: Set<string>;
|
|
2220
2201
|
importedCss: Set<string>;
|
|
@@ -2247,7 +2228,7 @@ declare module 'rollup' {
|
|
|
2247
2228
|
}
|
|
2248
2229
|
}
|
|
2249
2230
|
//#endregion
|
|
2250
|
-
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.
|
|
2231
|
+
//#region ../../../../node_modules/.pnpm/vite@6.4.5_@types+node@24.19.2_jiti@2.7.0_less@4.9.1_lightningcss@1.30.2_sass@1.107.1_t_8ea963fdf6f230da68c5cacf71b7d6dc/node_modules/vite/dist/node/index.d.ts
|
|
2251
2232
|
interface Alias {
|
|
2252
2233
|
find: string | RegExp;
|
|
2253
2234
|
replacement: string;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import t from"node:fs";import n from"node:path";import r from"node:url";import{decodePreviewableId as i,defineSpecialTypes as a,generatePreviewableId as o,readOwnVersion as s}from"@cfp-studio/analyzer-api";import c from"@vitejs/plugin-react";import{polyfillNode as l}from"esbuild-plugin-polyfill-node";import{createAnalyzer as u}from"@cfp-studio/analyzer-api/analyzer";import{createFileSystemReader as d,createStackedReader as f}from"@cfp-studio/vfs";import p from"typescript";import{parseSerializableValue as m}from"@cfp-studio/serializable-values";import{extractArgs as h,extractCsf3Stories as g,extractStoriesInfo as _,resolvePreviewableId as v}from"@cfp-studio/storybook-helpers";import{EMPTY_OBJECT_TYPE as y,NODE_TYPE as b,UNKNOWN_TYPE as x,arrayType as ee,dereferenceType as S,functionType as C,helpers as w,maybeOptionalType as T,objectType as E,stripUnusedTypes as D}from"@cfp-studio/type-analyzer";function O(e,t){for(let n of e.statements)if(p.isExpressionStatement(n)&&p.isBinaryExpression(n.expression)&&n.expression.operatorToken.kind===p.SyntaxKind.EqualsToken&&p.isPropertyAccessExpression(n.expression.left)&&p.isIdentifier(n.expression.left.expression)){if(n.expression.left.expression.text!==t)continue;if(n.expression.left.name.text===`propTypes`)return n.expression.right}else if(p.isClassDeclaration(n)&&n.name){if(n.name.text!==t)continue;for(let e of n.members)if(p.isPropertyDeclaration(e)&&e.initializer&&e.name.getText()===`propTypes`)return e.initializer}return null}function k(e,t,n,r,i){let a=t.sourceFile(n),o=null;a&&(o=O(a,r));let s=null;return s=o?j(t,o):A(e,t,i),{props:s.type,types:{...s.collected}}}function A(e,t,n){let r=n.getParameters()[0];if(!r)return{type:y,collected:{}};if(!r.valueDeclaration)return{type:x,collected:{}};let i=t.checker.getTypeOfSymbolAtLocation(r,r.valueDeclaration);try{let{type:e,collected:n}=t.resolveType(i);if([e]=S(e,n,[]),e.kind===`object`&&p.isParameter(r.valueDeclaration)&&p.isObjectBindingPattern(r.valueDeclaration.name)){let t=r.valueDeclaration.name,n=new Set,i=new Set,a=!1;for(let e of t.elements){if(e.dotDotDotToken){a=!0;break}let t=e.propertyName||e.name;if(!p.isIdentifier(t)){a=!0;break}n.add(t.text),e.initializer&&i.add(t.text)}a||(e=E(Object.fromEntries(Object.entries(e.fields).filter(([e])=>n.has(e)).map(([e,t])=>[e,T(t,i.has(e))]))))}return{type:e,collected:n}}catch(n){e.warn(`Unable to resolve props type for ${t.checker.typeToString(i)}`),e.error(n.toString())}return{type:x,collected:{}}}function j(e,t){let n=e.checker.getTypeAtLocation(t),r={},i={};for(let t of n.getProperties())r[t.name]=(()=>{if(!t.valueDeclaration)return x;let n=e.checker.getTypeAtLocation(t.valueDeclaration),r=e.resolveTypeArguments(n),a=r.types[0];return a?(i={...i,...r.collected},T(a,n.symbol.name===`Requireable`)):x})();let a=E(r);return{type:a,collected:D(i,[a])}}async function M(e,t,r,a){let s=t.sourceFile(a);if(!s)return[];let c=[];for(let e of s.statements)if(p.isExportAssignment(e)){if(p.isIdentifier(e.expression))continue;c.push([`default`,e,e.expression])}else if(p.isVariableStatement(e))for(let t of e.declarationList.declarations)!p.isIdentifier(t.name)||!t.initializer||c.push([t.name.text,e,t.initializer]);else if(p.isFunctionDeclaration(e)){let t=!!e.modifiers?.find(e=>e.kind===p.SyntaxKind.ExportKeyword)&&!!e.modifiers?.find(e=>e.kind===p.SyntaxKind.DefaultKeyword),n=e.name?.text;(t||n)&&c.push([n||`default`,e,e])}else p.isClassDeclaration(e)&&e.name&&c.push([e.name.text,e,e]);let l=_(s);e.debug(`**storiresInfo: ${l}`);let u=[],d=h(s),f=w.extractExportedNames(s);async function v(n,i,o){if(o===`default`&&l)return null;let s=d[o],c=o===`default`||!!f[o],u=P(t.checker,i);if(l&&c&&(s||u?.parameters.length===0)){let i=N(e,t,r,l.component);return{...n,analyze:async()=>({args:s?{sourcePosition:{start:s.getStart(),end:s.getEnd()},value:await m(s)}:null}),associatedComponent:i}}return u?{...n,exported:c,analyze:async()=>k(e,t,a,o,u)}:null}for(let[e,t,i]of c){let s=await v({id:o({filePath:n.relative(r,a),name:e}),sourcePosition:{start:t.getStart(),end:t.getEnd()}},i,e);s&&u.push(s)}return[...u,...await g(r,t,s,async a=>{let{filePath:o}=i(a),s=(await M(e,t,r,n.join(r,o))).find(e=>e.id===a);return!s||!(`exported`in s)?{props:x,types:{}}:s.analyze()})]}function N(e,t,r,a){let o=v(r,t.checker,a);return a&&o?{id:o,analyze:async()=>{let s=P(t.checker,a);if(!s)return{props:x,types:{}};let{filePath:c,name:l}=i(o);return k(e,t,n.join(r,c),l,s)}}:null}function P(e,t){let n=e.getTypeAtLocation(t);if(n.flags===p.TypeFlags.Any&&p.isCallExpression(t)&&p.isPropertyAccessExpression(t.expression)&&p.isIdentifier(t.expression.name)&&t.expression.name.text===`bind`){let r=e.getSymbolAtLocation(t.expression.expression);r?.valueDeclaration&&p.isVariableDeclaration(r.valueDeclaration)&&r.valueDeclaration.initializer&&(n=e.getTypeAtLocation(r.valueDeclaration.initializer))}for(let e of n.getCallSignatures())if(F(e.getReturnType()))return e;if(n.symbol){let r=e.getTypeOfSymbolAtLocation(n.symbol,t);for(let e of r.getConstructSignatures())if(e.getReturnType().getProperty(`render`))return e}return null}function F(e){return!!L(e)}const I=new Set([`Element`,`ReactElement`]);function L(e){if(e.isUnion()){for(let t of e.types)if(L(t))return!0}return I.has(e.symbol?.getEscapedName().toString())}const R=a({Component:b,ComponentClass:C(b),FunctionComponent:C(b),ReactElement:b,ReactNode:b,ReactNodeArray:ee(b),ReactPortal:b}),z=u({typeAnalyzerOptions:({reader:e,rootDir:i})=>{let a=r.fileURLToPath(new URL(`.`,import.meta.url)),o=n.join(a,`..`,`types`),s=n.join(a,`..`,`node_modules`),c=t.existsSync(o)?o:s;return{reader:f([e,d({mapping:{from:c,to:n.join(i,`node_modules`)},watch:!1}),...c===o?[d({mapping:{from:o,to:n.join(i,`node_modules`,`@types`)},watch:!1})]:[]]),specialTypes:R,tsCompilerOptions:{jsx:p.JsxEmit.ReactJSX,jsxImportSource:`react`}}},crawlFile:({logger:e,resolver:t,rootDir:n,absoluteFilePath:r})=>M(e,t,n,r)}),B={line:`data-inspector-line`,column:`data-inspector-column`,relativePath:`data-inspector-relative-path`};function V(e){return e.includes(B.relativePath)}function H(e,t){if(!e.includes(`<`)||V(e))return;let n=p.createSourceFile(t.relativePath,e,p.ScriptTarget.Latest,!0,p.ScriptKind.TSX),r=[],i=e=>{if(p.isJsxElement(e)||p.isJsxSelfClosingElement(e)){let i=p.isJsxElement(e)?e.openingElement:e,a=i.tagName.getStart(n),{line:o,character:s}=n.getLineAndCharacterOfPosition(a),c=i.tagName.getEnd(),l=` ${B.line}="${o+1}" ${B.column}="${s+1}" ${B.relativePath}="${U(t.relativePath)}"`;r.push({at:c,text:l})}p.forEachChild(e,i)};if(i(n),r.length===0)return;r.sort((e,t)=>t.at-e.at);let a=e;for(let{at:e,text:t}of r)a=a.slice(0,e)+t+a.slice(e);return a}function U(e){return e.replace(/&/g,`&`).replace(/"/g,`"`)}const W=/import (\* as )?React[ ,]/;function G(){return{name:`previewjs:react-js-imports`,async transform(e,t){return t.includes(`node_modules`)||n.extname(t)!==`.js`||W.test(e)?e:`import React from 'react';${e}`}}}const K=e(import.meta.url),q=[`fsevents`];function J(e,t){if(t.react)return{};let r={};for(let t of[`react`,`react-dom`]){let i=Y(t,e,$);i&&(r[t]=n.dirname(i))}return r}function Y(t,n,r){let i=`${t}/package.json`;try{return K.resolve(i,{paths:[n]})}catch{}for(let t of r)try{return e(K.resolve(t,{paths:[n]})).resolve(i)}catch{}return null}function X(t,n,r=[]){let i=Z(()=>K.resolve(t,{paths:[n]}));if(i)return i;for(let i of r){let r=Z(()=>e(K.resolve(i,{paths:[n]})).resolve(t));if(r)return r}return null}function Z(e){try{let r=e();if(!r)return null;let i=n.dirname(r);for(;i!==n.dirname(i);){let e=n.join(i,`package.json`);if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,`utf8`));return typeof n.version==`string`?n.version:null}i=n.dirname(i)}return null}catch{return null}}const Q=[`src/.umi/**`,`src/.umi-production/**`,`src/.umi-test/**`,`src/.umi-tmp/**`],$=[`umi`,`@umijs/max`];function te(){let e=``;return{name:`previewjs:inspector-attrs`,enforce:`pre`,configResolved(t){e=t.root},transform(t,r){let i=r.split(`?`)[0]??r;if(!/\.[jt]sx$/.test(i)||i.includes(`node_modules`)||i.includes(`__previewjs__`)||i.includes(`__previewjs_internal__`))return;let a=H(t,{relativePath:n.relative(e,i).split(n.sep).join(`/`)});if(a!==void 0)return{code:a,map:null}}}}const ne={info:{apiVersion:5,version:s(import.meta.url),name:`@cfp-studio/plugin-react`},isCompatible:async(e,t)=>{let n=await e.react?.readInstalledVersion();if(!n&&t&&(n=X(`react`,t,$)),!n)return!1;let[r,i]=n.split(`.`).map(e=>Number.parseInt(e));return Number.isNaN(r)||Number.isNaN(i)?!1:r>=17||r===16&&i>=14},async create({rootDir:e,reader:i,logger:a,dependencies:o}){let s=r.fileURLToPath(new URL(`.`,import.meta.url)),u=await o.umi?.readInstalledVersion()??await o[`@umijs/max`]?.readInstalledVersion(),d=u?Number.parseInt(u.split(`.`)[0]??`0`)>=4:!1,f=z({rootDir:e,reader:i,logger:a}),p=n.join(s,`..`,`preview`),m=J(e,o),h=`/__previewjs_internal__/renderer/shims/umi.tsx`,g=n.join(e,`src`),_={};if(d){t.existsSync(g)&&(_[`@`]=g);let r=n.join(g,`.umi`);t.existsSync(r)?_[`@@`]=r:a.debug(`umi: 跳过 @@ 别名,src/.umi 不存在(dev server 未启动)`);let i=(()=>{try{return n.dirname(K.resolve(`umi`,{paths:[e]}))}catch{try{return n.dirname(K.resolve(`@umijs/max`,{paths:[e]}))}catch{return e}}})();for(let e of[`react-router`,`react-router-dom`])try{let t=K.resolve(`${e}/package.json`,{paths:[i]});_[e]=n.dirname(t)}catch{a.debug(`umi: 跳过 ${e} 别名,解析不到实际安装位置`)}}return{defaultWrapperPath:`__previewjs__/Wrapper.tsx`,previewDirPath:p,ignoredPaths:d?Q:[],...f,viteConfig:e=>{let t=e.find(e=>e.name.startsWith(`vite:react-`));return{optimizeDeps:{...d?{exclude:q}:{},esbuildOptions:{plugins:o.next?[l()]:[]}},resolve:{alias:{"react-native":`react-native-web`,...m,...d?{umi:h,"@umijs/max":h,..._}:{}}},plugins:[te(),G(),...e,...t?[]:[c()],{name:`previewjs:update-react-import`,async transform(e,t){if(!t.endsWith(`__previewjs_internal__/renderer/index.tsx`))return;let n=Number.parseInt(await o.react?.readInstalledVersion()||`0`);return e.replace(/__PREVIEWJS_PLUGIN_REACT_IMPORT_PATH__/g,n>=18?`./render-18`:`./render-16`)}}]}}}}};export{Q as UMI_GENERATED_DIR_GLOBS,q as UMI_NATIVE_MODULES_TO_EXCLUDE,ne as default,X as resolveInstalledVersion};
|
|
1
|
+
import{createRequire as e}from"node:module";import t from"node:fs";import n from"node:path";import r from"node:url";import{decodePreviewableId as i,defineSpecialTypes as a,generatePreviewableId as o,readOwnVersion as s,shouldSkipFileForOtherFramework as c}from"@cfp-studio/analyzer-api";import l from"@vitejs/plugin-react";import{polyfillNode as u}from"esbuild-plugin-polyfill-node";import{createAnalyzer as d}from"@cfp-studio/analyzer-api/analyzer";import{createFileSystemReader as f,createStackedReader as p}from"@cfp-studio/vfs";import m from"typescript";import{parseSerializableValue as h}from"@cfp-studio/serializable-values";import{extractArgs as g,extractCsf3Stories as _,extractStoriesInfo as v,resolvePreviewableId as y}from"@cfp-studio/storybook-helpers";import{EMPTY_OBJECT_TYPE as b,NODE_TYPE as x,UNKNOWN_TYPE as S,arrayType as C,dereferenceType as w,functionType as T,helpers as E,maybeOptionalType as D,objectType as O,stripUnusedTypes as k}from"@cfp-studio/type-analyzer";function ee(e,t){for(let n of e.statements)if(m.isExpressionStatement(n)&&m.isBinaryExpression(n.expression)&&n.expression.operatorToken.kind===m.SyntaxKind.EqualsToken&&m.isPropertyAccessExpression(n.expression.left)&&m.isIdentifier(n.expression.left.expression)){if(n.expression.left.expression.text!==t)continue;if(n.expression.left.name.text===`propTypes`)return n.expression.right}else if(m.isClassDeclaration(n)&&n.name){if(n.name.text!==t)continue;for(let e of n.members)if(m.isPropertyDeclaration(e)&&e.initializer&&e.name.getText()===`propTypes`)return e.initializer}return null}function A(e,t,n,r,i){let a=t.sourceFile(n),o=null;a&&(o=ee(a,r));let s=null;return s=o?M(t,o):j(e,t,i),{props:s.type,types:{...s.collected}}}function j(e,t,n){let r=n.getParameters()[0];if(!r)return{type:b,collected:{}};if(!r.valueDeclaration)return{type:S,collected:{}};let i=t.checker.getTypeOfSymbolAtLocation(r,r.valueDeclaration);try{let{type:e,collected:n}=t.resolveType(i);if([e]=w(e,n,[]),e.kind===`object`&&m.isParameter(r.valueDeclaration)&&m.isObjectBindingPattern(r.valueDeclaration.name)){let t=r.valueDeclaration.name,n=new Set,i=new Set,a=!1;for(let e of t.elements){if(e.dotDotDotToken){a=!0;break}let t=e.propertyName||e.name;if(!m.isIdentifier(t)){a=!0;break}n.add(t.text),e.initializer&&i.add(t.text)}a||(e=O(Object.fromEntries(Object.entries(e.fields).filter(([e])=>n.has(e)).map(([e,t])=>[e,D(t,i.has(e))]))))}return{type:e,collected:n}}catch(n){e.warn(`Unable to resolve props type for ${t.checker.typeToString(i)}`),e.error(n.toString())}return{type:S,collected:{}}}function M(e,t){let n=e.checker.getTypeAtLocation(t),r={},i={};for(let t of n.getProperties())r[t.name]=(()=>{if(!t.valueDeclaration)return S;let n=e.checker.getTypeAtLocation(t.valueDeclaration),r=e.resolveTypeArguments(n),a=r.types[0];return a?(i={...i,...r.collected},D(a,n.symbol.name===`Requireable`)):S})();let a=O(r);return{type:a,collected:k(i,[a])}}async function N(e,t,r,a){let s=t.sourceFile(a);if(!s||c(m,s,[`react`,`react-dom`],[`solid-js`]))return[];let l=[];for(let e of s.statements)if(m.isExportAssignment(e)){if(m.isIdentifier(e.expression))continue;l.push([`default`,e,e.expression])}else if(m.isVariableStatement(e))for(let t of e.declarationList.declarations)!m.isIdentifier(t.name)||!t.initializer||l.push([t.name.text,e,t.initializer]);else if(m.isFunctionDeclaration(e)){let t=!!e.modifiers?.find(e=>e.kind===m.SyntaxKind.ExportKeyword)&&!!e.modifiers?.find(e=>e.kind===m.SyntaxKind.DefaultKeyword),n=e.name?.text;(t||n)&&l.push([n||`default`,e,e])}else m.isClassDeclaration(e)&&e.name&&l.push([e.name.text,e,e]);let u=v(s);e.debug(`**storiresInfo: ${u}`);let d=[],f=g(s),p=E.extractExportedNames(s);async function y(n,i,o){if(o===`default`&&u)return null;let s=f[o],c=o===`default`||!!p[o],l=P(t.checker,i);if(u&&c&&(s||l?.parameters.length===0)){let i=te(e,t,r,u.component);return{...n,analyze:async()=>({args:s?{sourcePosition:{start:s.getStart(),end:s.getEnd()},value:await h(s)}:null}),associatedComponent:i}}return l?{...n,exported:c,analyze:async()=>A(e,t,a,o,l)}:null}for(let[e,t,i]of l){let s=await y({id:o({filePath:n.relative(r,a),name:e}),sourcePosition:{start:t.getStart(),end:t.getEnd()}},i,e);s&&d.push(s)}return[...d,...await _(r,t,s,async a=>{let{filePath:o}=i(a),s=(await N(e,t,r,n.join(r,o))).find(e=>e.id===a);return!s||!(`exported`in s)?{props:S,types:{}}:s.analyze()})]}function te(e,t,r,a){let o=y(r,t.checker,a);return a&&o?{id:o,analyze:async()=>{let s=P(t.checker,a);if(!s)return{props:S,types:{}};let{filePath:c,name:l}=i(o);return A(e,t,n.join(r,c),l,s)}}:null}function P(e,t){let n=e.getTypeAtLocation(t);if(n.flags===m.TypeFlags.Any&&m.isCallExpression(t)&&m.isPropertyAccessExpression(t.expression)&&m.isIdentifier(t.expression.name)&&t.expression.name.text===`bind`){let r=e.getSymbolAtLocation(t.expression.expression);r?.valueDeclaration&&m.isVariableDeclaration(r.valueDeclaration)&&r.valueDeclaration.initializer&&(n=e.getTypeAtLocation(r.valueDeclaration.initializer))}for(let e of n.getCallSignatures())if(F(e.getReturnType()))return e;if(n.symbol){let r=e.getTypeOfSymbolAtLocation(n.symbol,t);for(let e of r.getConstructSignatures())if(e.getReturnType().getProperty(`render`))return e}return null}function F(e){return L(e)}const I=new Set([`Element`,`ReactElement`]);function L(e){if(e.isUnion()){for(let t of e.types)if(L(t))return!0}return I.has(e.symbol?.getEscapedName().toString())}const R=a({Component:x,ComponentClass:T(x),FunctionComponent:T(x),ReactElement:x,ReactNode:x,ReactNodeArray:C(x),ReactPortal:x}),z=d({typeAnalyzerOptions:({reader:e,rootDir:i})=>{let a=r.fileURLToPath(new URL(`.`,import.meta.url)),o=n.join(a,`..`,`types`),s=n.join(a,`..`,`node_modules`),c=t.existsSync(o)?o:s;return{reader:p([e,f({mapping:{from:c,to:n.join(i,`node_modules`)},watch:!1}),...c===o?[f({mapping:{from:o,to:n.join(i,`node_modules`,`@types`)},watch:!1})]:[]]),specialTypes:R,tsCompilerOptions:{jsx:m.JsxEmit.ReactJSX,jsxImportSource:`react`}}},crawlFile:({logger:e,resolver:t,rootDir:n,absoluteFilePath:r})=>N(e,t,n,r)}),B={line:`data-inspector-line`,column:`data-inspector-column`,relativePath:`data-inspector-relative-path`};function V(e){return e.includes(B.relativePath)}function H(e,t){if(!e.includes(`<`)||V(e))return;let n=m.createSourceFile(t.relativePath,e,m.ScriptTarget.Latest,!0,m.ScriptKind.TSX),r=[],i=e=>{if(m.isJsxElement(e)||m.isJsxSelfClosingElement(e)){let i=m.isJsxElement(e)?e.openingElement:e,a=i.tagName.getStart(n),{line:o,character:s}=n.getLineAndCharacterOfPosition(a),c=i.tagName.getEnd(),l=` ${B.line}="${o+1}" ${B.column}="${s+1}" ${B.relativePath}="${U(t.relativePath)}"`;r.push({at:c,text:l})}m.forEachChild(e,i)};if(i(n),r.length===0)return;r.sort((e,t)=>t.at-e.at);let a=e;for(let{at:e,text:t}of r)a=a.slice(0,e)+t+a.slice(e);return a}function U(e){return e.replace(/&/g,`&`).replace(/"/g,`"`)}const W=/import (\* as )?React[ ,]/;function G(){return{name:`previewjs:react-js-imports`,async transform(e,t){return t.includes(`node_modules`)||n.extname(t)!==`.js`||W.test(e)?e:`import React from 'react';${e}`}}}const K=e(import.meta.url),q=[`fsevents`];function J(e,t){if(t.react)return{};let r={};for(let t of[`react`,`react-dom`]){let i=Y(t,e,$);i&&(r[t]=n.dirname(i))}return r}function Y(t,n,r){let i=`${t}/package.json`;try{return K.resolve(i,{paths:[n]})}catch{}for(let t of r)try{return e(K.resolve(t,{paths:[n]})).resolve(i)}catch{}return null}function X(t,n,r=[]){let i=Z(()=>K.resolve(t,{paths:[n]}));if(i)return i;for(let i of r){let r=Z(()=>e(K.resolve(i,{paths:[n]})).resolve(t));if(r)return r}return null}function Z(e){try{let r=e();if(!r)return null;let i=n.dirname(r);for(;i!==n.dirname(i);){let e=n.join(i,`package.json`);if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,`utf8`));return typeof n.version==`string`?n.version:null}i=n.dirname(i)}return null}catch{return null}}const Q=[`src/.umi/**`,`src/.umi-production/**`,`src/.umi-test/**`,`src/.umi-tmp/**`],$=[`umi`,`@umijs/max`];function ne(){let e=``;return{name:`previewjs:inspector-attrs`,enforce:`pre`,configResolved(t){e=t.root},transform(t,r){let i=r.split(`?`)[0]??r;if(!/\.[jt]sx$/.test(i)||i.includes(`node_modules`)||i.includes(`__previewjs__`)||i.includes(`__previewjs_internal__`))return;let a=H(t,{relativePath:n.relative(e,i).split(n.sep).join(`/`)});if(a!==void 0)return{code:a,map:null}}}}const re={info:{apiVersion:5,version:s(import.meta.url),name:`@cfp-studio/plugin-react`},isCompatible:async(e,t)=>{let n=await e.react?.readInstalledVersion();if(!n&&t&&(n=X(`react`,t,$)),!n)return!1;let[r,i]=n.split(`.`).map(e=>Number.parseInt(e));return Number.isNaN(r)||Number.isNaN(i)?!1:r>=17||r===16&&i>=14},async create({rootDir:e,reader:i,logger:a,dependencies:o}){let s=r.fileURLToPath(new URL(`.`,import.meta.url)),c=await o.umi?.readInstalledVersion()??await o[`@umijs/max`]?.readInstalledVersion(),d=c?Number.parseInt(c.split(`.`)[0]??`0`)>=4:!1,f=z({rootDir:e,reader:i,logger:a}),p=n.join(s,`..`,`preview`),m=J(e,o),h=`/__previewjs_internal__/renderer/shims/umi.tsx`,g=n.join(e,`src`),_={};if(d){t.existsSync(g)&&(_[`@`]=g);let r=n.join(g,`.umi`);t.existsSync(r)?_[`@@`]=r:a.debug(`umi: 跳过 @@ 别名,src/.umi 不存在(dev server 未启动)`);let i=(()=>{try{return n.dirname(K.resolve(`umi`,{paths:[e]}))}catch{try{return n.dirname(K.resolve(`@umijs/max`,{paths:[e]}))}catch{return e}}})();for(let e of[`react-router`,`react-router-dom`])try{let t=K.resolve(`${e}/package.json`,{paths:[i]});_[e]=n.dirname(t)}catch{a.debug(`umi: 跳过 ${e} 别名,解析不到实际安装位置`)}}return{defaultWrapperPath:`__previewjs__/Wrapper.tsx`,previewDirPath:p,ignoredPaths:d?Q:[],...f,viteConfig:e=>{let t=e.find(e=>e.name.startsWith(`vite:react-`));return{optimizeDeps:{...d?{exclude:q}:{},esbuildOptions:{plugins:o.next?[u()]:[]}},resolve:{alias:{"react-native":`react-native-web`,...m,...d?{umi:h,"@umijs/max":h,..._}:{}}},plugins:[ne(),G(),...e,...t?[]:[l()],{name:`previewjs:update-react-import`,async transform(e,t){if(!t.endsWith(`__previewjs_internal__/renderer/index.tsx`))return;let n=Number.parseInt(await o.react?.readInstalledVersion()||`0`),r=n>=19?`./render-19`:n>=18?`./render-18`:`./render-16`;return e.replace(/__PREVIEWJS_PLUGIN_REACT_IMPORT_PATH__/g,r)}}]}}}}};export{Q as UMI_GENERATED_DIR_GLOBS,q as UMI_NATIVE_MODULES_TO_EXCLUDE,re as default,X as resolveInstalledVersion};
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cfp-studio/plugin-react",
|
|
3
|
-
"version": "17.3.
|
|
3
|
+
"version": "17.3.9",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
7
7
|
"preview",
|
|
8
|
+
"!preview/**/*.spec.ts*",
|
|
8
9
|
"types"
|
|
9
10
|
],
|
|
10
11
|
"type": "module",
|
|
@@ -15,12 +16,12 @@
|
|
|
15
16
|
"@vitejs/plugin-react": "4.3.4",
|
|
16
17
|
"esbuild-plugin-polyfill-node": "0.3.0",
|
|
17
18
|
"typescript": "5.9.3",
|
|
18
|
-
"@cfp-studio/api": "
|
|
19
|
-
"@cfp-studio/
|
|
19
|
+
"@cfp-studio/analyzer-api": "0.1.19",
|
|
20
|
+
"@cfp-studio/serializable-values": "9.0.10",
|
|
20
21
|
"@cfp-studio/storybook-helpers": "6.0.2",
|
|
21
|
-
"@cfp-studio/serializable-values": "9.0.8",
|
|
22
22
|
"@cfp-studio/vfs": "2.1.8",
|
|
23
|
-
"@cfp-studio/type-analyzer": "10.1.
|
|
23
|
+
"@cfp-studio/type-analyzer": "10.1.10",
|
|
24
|
+
"@cfp-studio/api": "16.1.2"
|
|
24
25
|
},
|
|
25
26
|
"devDependencies": {
|
|
26
27
|
"@playwright/test": "1.64.1",
|
|
@@ -34,9 +35,9 @@
|
|
|
34
35
|
"react-dom": "18.3.1",
|
|
35
36
|
"vite": "6.4.5",
|
|
36
37
|
"vitest": "5.0.5",
|
|
37
|
-
"@cfp-studio/iframe": "18.4.
|
|
38
|
+
"@cfp-studio/iframe": "18.4.14",
|
|
38
39
|
"@cfp-studio/testing": "14.0.1",
|
|
39
|
-
"@cfp-studio/core": "1.0.
|
|
40
|
+
"@cfp-studio/core": "1.0.20"
|
|
40
41
|
},
|
|
41
42
|
"engines": {
|
|
42
43
|
"node": ">=20"
|
package/preview/index.tsx
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { GetPropsFn, RendererLoader } from "@cfp-studio/iframe";
|
|
2
|
-
// @ts-ignore
|
|
3
|
-
import
|
|
2
|
+
// @ts-ignore —— 路径在构建期由 `src/index.ts` 的 transform 按 React 版本替换。
|
|
3
|
+
import * as rendererModule from "__PREVIEWJS_PLUGIN_REACT_IMPORT_PATH__";
|
|
4
4
|
import React from "react";
|
|
5
5
|
|
|
6
6
|
import { ErrorBoundary, expectErrorBoundary } from "./error-boundary";
|
|
@@ -60,7 +60,7 @@ export const loadRenderer: RendererLoader = async ({
|
|
|
60
60
|
if (shouldAbortRender()) {
|
|
61
61
|
return;
|
|
62
62
|
}
|
|
63
|
-
await render(
|
|
63
|
+
await rendererModule.render(
|
|
64
64
|
<Renderer
|
|
65
65
|
{...getProps({
|
|
66
66
|
presetGlobalProps: previewableModule.default?.args || {},
|
|
@@ -76,6 +76,16 @@ export const loadRenderer: RendererLoader = async ({
|
|
|
76
76
|
return;
|
|
77
77
|
}
|
|
78
78
|
if (errorBoundary.state.error) {
|
|
79
|
+
/**
|
|
80
|
+
* 照常抛 —— 但要让它走到 `runRenderer` 的**失败分支**:
|
|
81
|
+
* 那里会置 `lastRenderFailed = true`、清掉"渲染成功但内容为空"的提示,
|
|
82
|
+
* 且**不发** `rendered`。否则错误面板与"渲染完成"会同时出现。
|
|
83
|
+
*
|
|
84
|
+
* React 19 起,root 的 `onCaughtError` 已经先报过一次(详见
|
|
85
|
+
* `render-19.tsx`);重复的那次由 `runRenderer` 按 Error 上的
|
|
86
|
+
* `Symbol.for("cfp.preview.errorAlreadyReported")` 标记跳过。
|
|
87
|
+
* 而 HMR 路径不经过这里,只有 root 回调在报 —— 那条是唯一通路。
|
|
88
|
+
*/
|
|
79
89
|
throw errorBoundary.state.error;
|
|
80
90
|
}
|
|
81
91
|
if (Previewable.play) {
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { Root } from "react-dom/client";
|
|
2
|
+
import { createRoot } from "react-dom/client";
|
|
3
|
+
|
|
4
|
+
import { rootContainer } from "./root";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* React 19 专用根。
|
|
8
|
+
*
|
|
9
|
+
* ## 为什么需要单独一份(而不是继续用 `render-18`)
|
|
10
|
+
*
|
|
11
|
+
* React 19 改了渲染期错误的分发方式:**不再 rethrow 到 `window`**,改由 root 的
|
|
12
|
+
* `onCaughtError` / `onUncaughtError` 回调处理。而 CFP 原来的上报通路是
|
|
13
|
+
* 「`runRenderer` → `render()` 抛错 → catch → `reportEvent({kind:"error"})`」,
|
|
14
|
+
* 它只覆盖**经过 render 入口**的路径。
|
|
15
|
+
*
|
|
16
|
+
* HMR 更新时 react-refresh 在模块内热替换组件、由 React 自己重渲染,完全绕过入口 ——
|
|
17
|
+
* 于是错误只到 console,宿主侧收不到(2026-11-19 实测:`getDerivedStateFromError`
|
|
18
|
+
* 与 `componentDidCatch` 都正常调用、错误面板也画出来了,但 `state.errors` 为空)。
|
|
19
|
+
* 详见 `docs/analysis/react19-support.md`。
|
|
20
|
+
*
|
|
21
|
+
* 所以在 root 上挂回调,把错误直接送进 iframe 事件通道。
|
|
22
|
+
*
|
|
23
|
+
* ## 去重
|
|
24
|
+
*
|
|
25
|
+
* 初始加载路径下 `preview/index.tsx` 仍会把同一个错误对象 `throw` 出去(为了走
|
|
26
|
+
* `runRenderer` 的失败分支:置 `lastRenderFailed`、清空渲染提示、且**不**发
|
|
27
|
+
* `rendered`)。而这里已经报过一次 —— 所以上报时给 Error 打上标记,
|
|
28
|
+
* `runRenderer` 的 catch 看到标记就不再报第二次。
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** 已上报标记。用 `Symbol.for` 而非模块内 Symbol:iframe 侧的 catch 要认同一个键。 */
|
|
32
|
+
export const ERROR_REPORTED = Symbol.for("cfp.preview.errorAlreadyReported");
|
|
33
|
+
|
|
34
|
+
/** 告诉 `preview/index.tsx`:错误已由 root 回调上报(内容仅用于文档化,判定靠标记)。 */
|
|
35
|
+
export const reportsErrorsViaRoot = true;
|
|
36
|
+
|
|
37
|
+
function report(error: unknown, componentStack: string | undefined) {
|
|
38
|
+
const isError = error instanceof Error;
|
|
39
|
+
// 与 `runRenderer` 现有格式保持一致(`stack` 优先):多个用例按
|
|
40
|
+
// `"Error: Expected error"` 这样的前缀匹配,换格式会让它们全部失配。
|
|
41
|
+
const message = isError ? error.stack || error.message : String(error);
|
|
42
|
+
/**
|
|
43
|
+
* **自己打一条 error 级日志。**
|
|
44
|
+
*
|
|
45
|
+
* React 19 的行为:一旦你提供了 `onCaughtError`,它就**不再**打印默认的
|
|
46
|
+
* 「The above error occurred in <X>. React will try to recreate this component tree…」。
|
|
47
|
+
* 而在此之前,那条 console.error 是 CFP 的 `Output.PreviewConsole` 里唯一的错误痕迹。
|
|
48
|
+
*
|
|
49
|
+
* 不补的话用户会看到「错误面板出现了,但日志频道是空的」—— 排查时少一条关键线索。
|
|
50
|
+
* 措辞用我们自己的(`[renderer] <原始错误>`),不照抄 React 的句子:
|
|
51
|
+
* 那句话属于 React 的实现细节,随版本变,绑定它只会让日志再次失真。
|
|
52
|
+
*/
|
|
53
|
+
// 带上 componentStack:它才是「哪个组件抛的」的答案(React 19 抑制掉的那句
|
|
54
|
+
// 「The above error occurred in the <X> component」原来承担这个职责)。
|
|
55
|
+
console.error(`[renderer] ${isError ? error.message : String(error)}${componentStack ? `\n${componentStack}` : ""}`);
|
|
56
|
+
|
|
57
|
+
window.__PREVIEWJS_IFRAME__?.reportEvent({
|
|
58
|
+
kind: "error",
|
|
59
|
+
source: "renderer",
|
|
60
|
+
message: componentStack ? `${message}\n${componentStack}` : message,
|
|
61
|
+
});
|
|
62
|
+
if (isError) {
|
|
63
|
+
(error as unknown as Record<symbol, boolean>)[ERROR_REPORTED] = true;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** React 19 的 root 选项(本包的 `@types/react-dom` 是 18.x,没有这两个字段)。 */
|
|
68
|
+
interface React19RootOptions {
|
|
69
|
+
onCaughtError?: (error: unknown, errorInfo: { componentStack?: string }) => void;
|
|
70
|
+
onUncaughtError?: (error: unknown, errorInfo: { componentStack?: string }) => void;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
let root: Root | null = null;
|
|
74
|
+
|
|
75
|
+
export function render(node: JSX.Element) {
|
|
76
|
+
if (!root) {
|
|
77
|
+
const options: React19RootOptions = {
|
|
78
|
+
// 被 ErrorBoundary 捕获:报给宿主。**面板由 boundary 自己画**(`componentDidCatch`
|
|
79
|
+
// → `renderErrorPanel`),这里不重复画,否则会叠两层遮罩。
|
|
80
|
+
onCaughtError: (error, errorInfo) => report(error, errorInfo?.componentStack),
|
|
81
|
+
// 没有 boundary 兜住(例如 boundary 自身抛错):同样上报。这时没有面板,
|
|
82
|
+
// 宿主侧的 ErrorPage 就是用户能看到的唯一信息。
|
|
83
|
+
onUncaughtError: (error, errorInfo) => report(error, errorInfo?.componentStack),
|
|
84
|
+
};
|
|
85
|
+
// `@types/react-dom` 在本包仍是 18.x(要同时支持 16/17/18),这两个字段不在其类型里。
|
|
86
|
+
// 类型断言只影响类型层,运行时由 React 19 自己读取。
|
|
87
|
+
root = createRoot(rootContainer, options as unknown as Parameters<typeof createRoot>[1]);
|
|
88
|
+
}
|
|
89
|
+
root.render(node);
|
|
90
|
+
}
|
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
|
|
3
|
-
import { generatePath, matchPath, resolvePath } from "./umi.js";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* 对照测试:shim 里 react-router 纯函数的转导出必须与 `react-router@6.3.0`
|
|
7
|
-
* 的**真实输出**一致。
|
|
8
|
-
*
|
|
9
|
-
* 每个期望值都是在真实包上跑出来的(不是手写的猜测):
|
|
10
|
-
*
|
|
11
|
-
* ```sh
|
|
12
|
-
* node -e "const rr=require('<...>/react-router/main.js'); console.log(rr.matchPath('/users/:id','/users/42'))"
|
|
13
|
-
* ```
|
|
14
|
-
*
|
|
15
|
-
* ## 为什么这份测试重要
|
|
16
|
-
*
|
|
17
|
-
* 早期 shim 用的是「按 `/` 切段逐个比」的简版,错四处且都很难发现:
|
|
18
|
-
*
|
|
19
|
-
* | # | 输入 | 简版错误 | 后果 |
|
|
20
|
-
* | --- | --- | --- | --- |
|
|
21
|
-
* | 1 | 任意 | 返回 `params` 本体而非 `{ params, pathname, pathnameBase, pattern }` | 写 `match?.params.id` 的组件拿到 `undefined` |
|
|
22
|
-
* | 2 | `/files/*` + `/files/a/b/c` | 丢掉 splat 捕获 | 组件看到「匹配成功」但 `params["*"]` 为空 |
|
|
23
|
-
* | 3 | `/users/:id` + `/Users/42` | 大小写敏感 → `null` | 大小写不同的 URL 导不了 |
|
|
24
|
-
* | 4 | `/users/:id?` + `/users/42` | 产出 `"id?"` 这个脏键 | 参数名带问号 |
|
|
25
|
-
*
|
|
26
|
-
* 简版还让 e2e 用例 3e 断言的是 `match?.id`(简版的形状)—— 测试是绿的,
|
|
27
|
-
* 但语义是错的。这份单测把真实形状固定下来。
|
|
28
|
-
*
|
|
29
|
-
* ## 为什么测试放在 `src/` 而不是 `preview/`
|
|
30
|
-
*
|
|
31
|
-
* `preview/` 整体被 `vitest.config.ts` 排除(里面是浏览器端渲染入口)。
|
|
32
|
-
* 这份用例虽然测的是 `preview/shims/umi.tsx`,但它只是普通函数、不碰 DOM,
|
|
33
|
-
* 从 `src/` 引用即可。
|
|
34
|
-
*/
|
|
35
|
-
describe("matchPath 与 react-router 6.3 对齐", () => {
|
|
36
|
-
it("返回 `{ params, pathname, pathnameBase, pattern }` 四键(不是 params 本体)", () => {
|
|
37
|
-
const match = matchPath("/users/:id", "/users/42");
|
|
38
|
-
expect(Object.keys(match ?? {}).sort()).toEqual(["params", "pathname", "pathnameBase", "pattern"]);
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
it("基本参数捕获", () => {
|
|
42
|
-
expect(matchPath("/users/:id", "/users/42")).toEqual({
|
|
43
|
-
params: { id: "42" },
|
|
44
|
-
pathname: "/users/42",
|
|
45
|
-
pathnameBase: "/users/42",
|
|
46
|
-
pattern: { path: "/users/:id", caseSensitive: false, end: true },
|
|
47
|
-
});
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
it("默认大小写不敏感(`caseSensitive: false`)", () => {
|
|
51
|
-
expect(matchPath("/users/:id", "/Users/42")?.params.id).toBe("42");
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
it("`caseSensitive: true` 时大小写敏感", () => {
|
|
55
|
-
expect(matchPath({ path: "/users/:id", caseSensitive: true }, "/Users/42")).toBeNull();
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
it('尾部 splat 是具名捕获组,值进 `params["*"]`', () => {
|
|
59
|
-
const match = matchPath("/files/*", "/files/a/b/c");
|
|
60
|
-
expect(match?.params["*"]).toBe("a/b/c");
|
|
61
|
-
// `pathnameBase` 不含 splat 部分。
|
|
62
|
-
expect(match?.pathnameBase).toBe("/files");
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
it("`/files/*` 也能匹配 `/files` 本身(splat 为空字符串,不是 undefined)", () => {
|
|
66
|
-
expect(matchPath("/files/*", "/files")?.params["*"]).toBe("");
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
it("`/users/:id/*` 同时捕获参数与 splat", () => {
|
|
70
|
-
const match = matchPath("/users/:id/*", "/users/42/extra/deep");
|
|
71
|
-
expect(match?.params.id).toBe("42");
|
|
72
|
-
expect(match?.params["*"]).toBe("extra/deep");
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
it("`end: false` 允许前缀匹配", () => {
|
|
76
|
-
expect(matchPath({ path: "/users", end: false }, "/users/42/extra")?.pathnameBase).toBe("/users");
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
it("默认 `end: true`:多出的段不匹配", () => {
|
|
80
|
-
expect(matchPath("/users/:id", "/users/42/extra")).toBeNull();
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
it("忽略尾部斜杠", () => {
|
|
84
|
-
expect(matchPath("/users/:id/", "/users/42")?.params.id).toBe("42");
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
it("根路径", () => {
|
|
88
|
-
expect(matchPath("/", "/")).toEqual({
|
|
89
|
-
params: {},
|
|
90
|
-
pathname: "/",
|
|
91
|
-
pathnameBase: "/",
|
|
92
|
-
pattern: { path: "/", caseSensitive: false, end: true },
|
|
93
|
-
});
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
it("纯 `*` 匹配任意路径", () => {
|
|
97
|
-
expect(matchPath("*", "/anything/at/all")?.params["*"]).toBe("anything/at/all");
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
it("URL 段会被解码", () => {
|
|
101
|
-
expect(matchPath("/u/:id", "/u/%E4%B8%AD")?.params.id).toBe("中");
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
it("malformed 百分号编码不抛错,原样返回", () => {
|
|
105
|
-
expect(matchPath("/u/:id", "/u/%ZZ")?.params.id).toBe("%ZZ");
|
|
106
|
-
});
|
|
107
|
-
|
|
108
|
-
it("`:id?` 在 v6 不是可选段,且不产出 `id?` 这种脏键", () => {
|
|
109
|
-
// 与真实 react-router 一致:`?` 被当作字面字符,匹配不上。
|
|
110
|
-
expect(matchPath("/users/:id?", "/users/42")).toBeNull();
|
|
111
|
-
expect(matchPath("/users/:id?", "/users")).toBeNull();
|
|
112
|
-
});
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
describe("resolvePath 与 react-router 6.3 对齐", () => {
|
|
116
|
-
const cases: Array<[string, string, string]> = [
|
|
117
|
-
["child", "/parent/", "/parent/child"],
|
|
118
|
-
["child", "/parent", "/parent/child"],
|
|
119
|
-
["../sibling", "/a/b/", "/a/sibling"],
|
|
120
|
-
["../../up", "/a/b/c", "/a/up"],
|
|
121
|
-
["./same", "/a/b", "/a/b/same"],
|
|
122
|
-
["", "/a/b", "/a/b"],
|
|
123
|
-
["/abs", "/a/b", "/abs"],
|
|
124
|
-
["child", "/", "/child"],
|
|
125
|
-
];
|
|
126
|
-
|
|
127
|
-
for (const [to, from, expected] of cases) {
|
|
128
|
-
it(`resolvePath(${JSON.stringify(to)}, ${JSON.stringify(from)}) → ${expected}`, () => {
|
|
129
|
-
expect(resolvePath(to, from).pathname).toBe(expected);
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
it("保留 search 与 hash(并补上前缀符号)", () => {
|
|
134
|
-
expect(resolvePath("x?q=1#h", "/base/")).toEqual({ pathname: "/base/x", search: "?q=1", hash: "#h" });
|
|
135
|
-
});
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
describe("generatePath 与 react-router 6.3 对齐", () => {
|
|
139
|
-
it("替换 `:param`", () => {
|
|
140
|
-
expect(generatePath("/users/:id/posts/:postId", { id: "7", postId: "9" })).toBe("/users/7/posts/9");
|
|
141
|
-
});
|
|
142
|
-
|
|
143
|
-
it("不做 URL 编码(中文原样)", () => {
|
|
144
|
-
expect(generatePath("/u/:id", { id: "中文" })).toBe("/u/中文");
|
|
145
|
-
});
|
|
146
|
-
|
|
147
|
-
it("支持尾部 splat", () => {
|
|
148
|
-
expect(generatePath("/files/*", { "*": "a/b" })).toBe("/files/a/b");
|
|
149
|
-
});
|
|
150
|
-
|
|
151
|
-
it("splat 为空时去掉末尾星号", () => {
|
|
152
|
-
expect(generatePath("/files/*", {})).toBe("/files");
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
it("缺失参数抛错(与真实实现一致)", () => {
|
|
156
|
-
expect(() => generatePath("/u/:id", {})).toThrow('Missing ":id" param');
|
|
157
|
-
});
|
|
158
|
-
});
|