@tanstack/start-server-core 1.121.16 → 1.121.17
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/package.json +4 -4
- package/dist/cjs/createRequestHandler.cjs +0 -50
- package/dist/cjs/createRequestHandler.cjs.map +0 -1
- package/dist/cjs/createRequestHandler.d.cts +0 -8
- package/dist/cjs/createStartHandler.cjs +0 -313
- package/dist/cjs/createStartHandler.cjs.map +0 -1
- package/dist/cjs/createStartHandler.d.cts +0 -7
- package/dist/cjs/h3.cjs +0 -355
- package/dist/cjs/h3.cjs.map +0 -1
- package/dist/cjs/h3.d.cts +0 -109
- package/dist/cjs/handlerCallback.cjs +0 -7
- package/dist/cjs/handlerCallback.cjs.map +0 -1
- package/dist/cjs/handlerCallback.d.cts +0 -9
- package/dist/cjs/index.cjs +0 -244
- package/dist/cjs/index.cjs.map +0 -1
- package/dist/cjs/index.d.cts +0 -12
- package/dist/cjs/loadVirtualModule.cjs +0 -39
- package/dist/cjs/loadVirtualModule.cjs.map +0 -1
- package/dist/cjs/loadVirtualModule.d.cts +0 -6
- package/dist/cjs/router-manifest.cjs +0 -49
- package/dist/cjs/router-manifest.cjs.map +0 -1
- package/dist/cjs/router-manifest.d.cts +0 -16
- package/dist/cjs/server-functions-handler.cjs +0 -148
- package/dist/cjs/server-functions-handler.cjs.map +0 -1
- package/dist/cjs/server-functions-handler.d.cts +0 -3
- package/dist/cjs/serverRoute.cjs +0 -102
- package/dist/cjs/serverRoute.cjs.map +0 -1
- package/dist/cjs/serverRoute.d.cts +0 -120
- package/dist/cjs/ssr-server.cjs +0 -247
- package/dist/cjs/ssr-server.cjs.map +0 -1
- package/dist/cjs/ssr-server.d.cts +0 -29
- package/dist/cjs/transformStreamWithRouter.cjs +0 -183
- package/dist/cjs/transformStreamWithRouter.cjs.map +0 -1
- package/dist/cjs/transformStreamWithRouter.d.cts +0 -6
- package/dist/cjs/tsrScript.cjs +0 -4
- package/dist/cjs/tsrScript.cjs.map +0 -1
- package/dist/cjs/tsrScript.d.cts +0 -1
- package/dist/cjs/virtual-modules.cjs +0 -9
- package/dist/cjs/virtual-modules.cjs.map +0 -1
- package/dist/cjs/virtual-modules.d.cts +0 -10
- package/dist/esm/createRequestHandler.d.ts +0 -8
- package/dist/esm/createRequestHandler.js +0 -50
- package/dist/esm/createRequestHandler.js.map +0 -1
- package/dist/esm/createStartHandler.d.ts +0 -7
- package/dist/esm/createStartHandler.js +0 -313
- package/dist/esm/createStartHandler.js.map +0 -1
- package/dist/esm/h3.d.ts +0 -109
- package/dist/esm/h3.js +0 -248
- package/dist/esm/h3.js.map +0 -1
- package/dist/esm/handlerCallback.d.ts +0 -9
- package/dist/esm/handlerCallback.js +0 -7
- package/dist/esm/handlerCallback.js.map +0 -1
- package/dist/esm/index.d.ts +0 -12
- package/dist/esm/index.js +0 -136
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/loadVirtualModule.d.ts +0 -6
- package/dist/esm/loadVirtualModule.js +0 -17
- package/dist/esm/loadVirtualModule.js.map +0 -1
- package/dist/esm/router-manifest.d.ts +0 -16
- package/dist/esm/router-manifest.js +0 -49
- package/dist/esm/router-manifest.js.map +0 -1
- package/dist/esm/server-functions-handler.d.ts +0 -3
- package/dist/esm/server-functions-handler.js +0 -148
- package/dist/esm/server-functions-handler.js.map +0 -1
- package/dist/esm/serverRoute.d.ts +0 -120
- package/dist/esm/serverRoute.js +0 -102
- package/dist/esm/serverRoute.js.map +0 -1
- package/dist/esm/ssr-server.d.ts +0 -29
- package/dist/esm/ssr-server.js +0 -247
- package/dist/esm/ssr-server.js.map +0 -1
- package/dist/esm/transformStreamWithRouter.d.ts +0 -6
- package/dist/esm/transformStreamWithRouter.js +0 -183
- package/dist/esm/transformStreamWithRouter.js.map +0 -1
- package/dist/esm/tsrScript.d.ts +0 -1
- package/dist/esm/tsrScript.js +0 -5
- package/dist/esm/tsrScript.js.map +0 -1
- package/dist/esm/virtual-modules.d.ts +0 -10
- package/dist/esm/virtual-modules.js +0 -9
- package/dist/esm/virtual-modules.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"serverRoute.js","sources":["../../src/serverRoute.ts"],"sourcesContent":["import { joinPaths, rootRouteId, trimPathLeft } from '@tanstack/router-core'\nimport type {\n Assign,\n Constrain,\n Expand,\n ResolveParams,\n RouteConstraints,\n TrimPathRight,\n} from '@tanstack/router-core'\nimport type {\n AnyRequestMiddleware,\n AssignAllServerContext,\n} from '@tanstack/start-client-core'\n\nexport function createServerFileRoute<\n TFilePath extends keyof ServerFileRoutesByPath,\n TParentRoute extends\n AnyServerRouteWithTypes = ServerFileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = ServerFileRoutesByPath[TFilePath]['id'],\n TPath extends\n RouteConstraints['TPath'] = ServerFileRoutesByPath[TFilePath]['path'],\n TFullPath extends\n RouteConstraints['TFullPath'] = ServerFileRoutesByPath[TFilePath]['fullPath'],\n TChildren = ServerFileRoutesByPath[TFilePath]['children'],\n>(_: TFilePath): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n return createServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>(\n undefined,\n )\n}\n\nexport interface ServerFileRoutesByPath {}\n\nexport interface ServerRouteOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n> {\n id: TId\n path: TPath\n pathname: TFullPath\n originalIndex: number\n getParentRoute?: () => TParentRoute\n middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>\n methods?: Record<\n string,\n ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any>\n >\n caseSensitive?: boolean\n}\n\nexport type ServerRouteManifest = {\n middleware: boolean\n methods: Record<string, { middleware: boolean }>\n}\n\nexport function createServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n>(\n __?: never,\n __opts?: Partial<\n ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>\n >,\n): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n const options = __opts || {}\n\n const route: ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> = {\n path: '' as TPath,\n id: '' as TId,\n fullPath: '' as TFullPath,\n to: '' as TrimPathRight<TFullPath>,\n options: options as ServerRouteOptions<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n any\n >,\n parentRoute: undefined as unknown as TParentRoute,\n _types: {} as ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined\n >,\n // children: undefined as TChildren,\n middleware: (middlewares) =>\n createServerRoute(undefined, {\n ...options,\n middleware: middlewares,\n }) as never,\n methods: (methodsOrGetMethods) => {\n const methods = (() => {\n if (typeof methodsOrGetMethods === 'function') {\n return methodsOrGetMethods(createMethodBuilder())\n }\n\n return methodsOrGetMethods\n })()\n\n return createServerRoute(undefined, {\n ...__opts,\n methods: methods as never,\n }) as never\n },\n update: (opts) =>\n createServerRoute(undefined, {\n ...options,\n ...opts,\n }),\n init: (opts: { originalIndex: number }): void => {\n options.originalIndex = opts.originalIndex\n\n const isRoot = !options.path && !options.id\n\n route.parentRoute = options.getParentRoute?.() as TParentRoute\n\n if (isRoot) {\n route.path = rootRouteId as TPath\n } else if (!(route.parentRoute as any)) {\n throw new Error(\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a ServerRoute instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPathLeft(path)\n }\n\n const customId = options.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n route.parentRoute.id === rootRouteId ? '' : route.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([route.parentRoute.fullPath, path])\n\n route.path = path as TPath\n route.id = id as TId\n route.fullPath = fullPath as TFullPath\n route.to = fullPath as TrimPathRight<TFullPath>\n },\n\n _addFileChildren: (children) => {\n if (Array.isArray(children)) {\n route.children = children as TChildren\n }\n\n if (typeof children === 'object' && children !== null) {\n route.children = Object.values(children) as TChildren\n }\n\n return route\n },\n\n _addFileTypes: <TFileTypes>() => route,\n }\n\n return route\n}\n\n// TODO this needs to be restricted to only allow middleware, no methods\n// TODO we also need to restrict pathless server routes to only allow middleware\nexport const createServerRootRoute = createServerRoute\n\nexport type ServerRouteAddFileChildrenFn<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TId extends RouteConstraints['TId'],\n in out TPath extends RouteConstraints['TPath'],\n in out TFullPath extends RouteConstraints['TFullPath'],\n in out TMiddlewares,\n in out TMethods,\n in out TChildren,\n> = (\n children: TChildren,\n) => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n>\n\nconst createMethodBuilder = <\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n>(\n __opts?: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n unknown,\n unknown\n >,\n): ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares> => {\n return {\n _options: (__opts || {}) as never,\n _types: {} as never,\n middleware: (middlewares) =>\n createMethodBuilder({\n ...__opts,\n middlewares,\n }) as never,\n handler: (handler) =>\n createMethodBuilder({\n ...__opts,\n handler: handler as never,\n }) as never,\n }\n}\n\nexport interface ServerRouteMethodBuilderOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n middlewares?: Constrain<\n TMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >\n}\n\nexport type CreateServerFileRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> = () => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n\nexport type AnyServerRouteWithTypes = ServerRouteWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> {\n _types: ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods\n >\n path: TPath\n id: TId\n fullPath: TFullPath\n to: TrimPathRight<TFullPath>\n parentRoute: TParentRoute\n children?: TChildren\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n update: (\n opts: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>,\n ) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n init: (opts: { originalIndex: number }) => void\n _addFileChildren: ServerRouteAddFileChildrenFn<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n _addFileTypes: () => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport interface ServerRouteTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n> {\n id: TId\n path: TPath\n fullPath: TFullPath\n middlewares: TMiddlewares\n methods: TMethods\n parentRoute: TParentRoute\n allContext: ResolveAllServerContext<TParentRoute, TMiddlewares>\n}\n\nexport type ResolveAllServerContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n> = unknown extends TParentRoute\n ? AssignAllServerContext<TMiddlewares>\n : Assign<\n TParentRoute['_types']['allContext'],\n AssignAllServerContext<TMiddlewares>\n >\n\nexport type AnyServerRoute = AnyServerRouteWithTypes\n\nexport interface ServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined,\n TChildren\n >,\n ServerRouteMiddleware<TParentRoute, TId, TPath, TFullPath, TChildren>,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n TChildren\n > {}\n\nexport interface ServerRouteMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> {\n middleware: <const TNewMiddleware>(\n middleware: Constrain<TNewMiddleware, ReadonlyArray<AnyRequestMiddleware>>,\n ) => ServerRouteAfterMiddleware<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TNewMiddleware,\n TChildren\n >\n}\n\nexport interface ServerRouteAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n undefined,\n TChildren\n >,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TChildren\n > {}\n\nexport interface ServerRouteMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> {\n methods: <const TMethods>(\n methodsOrGetMethods: Constrain<\n TMethods,\n ServerRouteMethodsOptions<TParentRoute, TFullPath, TMiddlewares>\n >,\n ) => ServerRouteAfterMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport type ServerRouteMethodsOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>\n | ((\n api: ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares>,\n ) => ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>)\n\nexport interface ServerRouteMethodsRecord<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n GET?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n POST?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PUT?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PATCH?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n DELETE?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n OPTIONS?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n HEAD?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n}\n\nexport type ServerRouteMethodRecordValue<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n any\n >\n | AnyRouteMethodsBuilder\n\nexport type ServerRouteVerb = (typeof ServerRouteVerbs)[number]\n\nexport const ServerRouteVerbs = [\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n] as const\n\nexport type ServerRouteMethodHandlerFn<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> = (\n ctx: ServerRouteMethodHandlerCtx<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >,\n) => TResponse | Promise<TResponse>\n\nexport interface ServerRouteMethodHandlerCtx<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n> {\n context: Expand<\n AssignAllMethodContext<TParentRoute, TMiddlewares, TMethodMiddlewares>\n >\n request: Request\n params: Expand<ResolveParams<TFullPath>>\n pathname: TFullPath\n}\n\nexport type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> =\n TMiddlewares extends ReadonlyArray<any>\n ? TMethodMiddlewares extends ReadonlyArray<any>\n ? readonly [...TMiddlewares, ...TMethodMiddlewares]\n : TMiddlewares\n : TMethodMiddlewares\n\nexport type AssignAllMethodContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n TMethodMiddlewares,\n> = ResolveAllServerContext<\n TParentRoute,\n MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>\n>\n\nexport type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteMethodBuilder<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n undefined\n >,\n ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined\n > {}\n\nexport interface ServerRouteMethodBuilderWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n _options: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n _types: ServerRouteMethodBuilderTypes<\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderTypes<\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n in out TResponse,\n> {\n middlewares: TMiddlewares\n methodMiddleware: TMethodMiddlewares\n fullPath: TFullPath\n response: TResponse\n}\n\nexport interface ServerRouteMethodBuilderMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n middleware: <const TNewMethodMiddlewares>(\n middleware: Constrain<\n TNewMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >,\n ) => ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TNewMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n > {}\n\nexport interface ServerRouteMethodBuilderHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n handler: <TResponse>(\n handler: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >,\n ) => ServerRouteMethodBuilderAfterHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n > {\n opts: ServerRouteMethod<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethod<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n middleware?: Constrain<TMiddlewares, Array<AnyRequestMiddleware>>\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >\n}\n\nexport interface ServerRouteAfterMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n > {\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n}\n"],"names":[],"mappings":";AAcO,SAAS,sBAUd,GAA2E;AACpE,SAAA,kBAEP;AACF;AA6BgB,SAAA,kBAOd,IACA,QAG6D;AACvD,QAAA,UAAU,UAAU,CAAC;AAE3B,QAAM,QAAqE;AAAA,IACzE,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,UAAU;AAAA,IACV,IAAI;AAAA,IACJ;AAAA,IAOA,aAAa;AAAA,IACb,QAAQ,CAAC;AAAA;AAAA,IAST,YAAY,CAAC,gBACX,kBAAkB,QAAW;AAAA,MAC3B,GAAG;AAAA,M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AAM,QAAQ,QAAQ,GAAG;AAC3B,cAAM,WAAW;AAAA,MAAA;AAGnB,UAAI,OAAO,aAAa,YAAY,aAAa,MAAM;AAC/C,cAAA,WAAW,OAAO,OAAO,QAAQ;AAAA,MAAA;AAGlC,aAAA;AAAA,IACT;AAAA,IAEA,eAAe,MAAkB;AAAA,EACnC;AAEO,SAAA;AACT;AAIO,MAAM,wBAAwB;AAsBrC,MAAM,sBAAsB,CAK1B,WAOoE;AAC7D,SAAA;AAAA,IACL,UAAW,UAAU,CAAC;AAAA,IACtB,QAAQ,CAAC;AAAA,IACT,YAAY,CAAC,gBACX,oBAAoB;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IAAA,CACD;AAAA,IACH,SAAS,CAAC,YACR,oBAAoB;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IACD,CAAA;AAAA,EACL;AACF;"}
|
package/dist/esm/ssr-server.d.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { ClientExtractedBaseEntry } from '@tanstack/start-client-core';
|
|
2
|
-
import { AnyRouteMatch, AnyRouter, DeferredPromise, Manifest } from '@tanstack/router-core';
|
|
3
|
-
export type ServerExtractedEntry = ServerExtractedStream | ServerExtractedPromise;
|
|
4
|
-
export interface ServerExtractedBaseEntry extends ClientExtractedBaseEntry {
|
|
5
|
-
id: number;
|
|
6
|
-
matchIndex: number;
|
|
7
|
-
}
|
|
8
|
-
export interface ServerExtractedStream extends ServerExtractedBaseEntry {
|
|
9
|
-
type: 'stream';
|
|
10
|
-
stream: ReadableStream;
|
|
11
|
-
}
|
|
12
|
-
export interface ServerExtractedPromise extends ServerExtractedBaseEntry {
|
|
13
|
-
type: 'promise';
|
|
14
|
-
promise: DeferredPromise<any>;
|
|
15
|
-
}
|
|
16
|
-
export declare function attachRouterServerSsrUtils(router: AnyRouter, manifest: Manifest | undefined): void;
|
|
17
|
-
export declare function dehydrateRouter(router: AnyRouter): void;
|
|
18
|
-
export declare function extractAsyncLoaderData(loaderData: any, ctx: {
|
|
19
|
-
match: AnyRouteMatch;
|
|
20
|
-
router: AnyRouter;
|
|
21
|
-
}): {
|
|
22
|
-
replaced: any;
|
|
23
|
-
extracted: ServerExtractedEntry[];
|
|
24
|
-
};
|
|
25
|
-
export declare function onMatchSettled(opts: {
|
|
26
|
-
router: AnyRouter;
|
|
27
|
-
match: AnyRouteMatch;
|
|
28
|
-
}): void;
|
|
29
|
-
export declare function replaceBy<T>(obj: T, cb: (value: any, path: Array<string>) => any, path?: Array<string>): T;
|
package/dist/esm/ssr-server.js
DELETED
|
@@ -1,247 +0,0 @@
|
|
|
1
|
-
import warning from "tiny-warning";
|
|
2
|
-
import { pick, TSR_DEFERRED_PROMISE, isPlainObject, isPlainArray, defer } from "@tanstack/router-core";
|
|
3
|
-
import jsesc from "jsesc";
|
|
4
|
-
import { startSerializer } from "@tanstack/start-client-core";
|
|
5
|
-
import minifiedTsrBootStrapScript from "./tsrScript.js";
|
|
6
|
-
function attachRouterServerSsrUtils(router, manifest) {
|
|
7
|
-
router.ssr = {
|
|
8
|
-
manifest,
|
|
9
|
-
serializer: startSerializer
|
|
10
|
-
};
|
|
11
|
-
router.serverSsr = {
|
|
12
|
-
injectedHtml: [],
|
|
13
|
-
streamedKeys: /* @__PURE__ */ new Set(),
|
|
14
|
-
injectHtml: (getHtml) => {
|
|
15
|
-
const promise = Promise.resolve().then(getHtml);
|
|
16
|
-
router.serverSsr.injectedHtml.push(promise);
|
|
17
|
-
router.emit({
|
|
18
|
-
type: "onInjectedHtml",
|
|
19
|
-
promise
|
|
20
|
-
});
|
|
21
|
-
return promise.then(() => {
|
|
22
|
-
});
|
|
23
|
-
},
|
|
24
|
-
injectScript: (getScript, opts) => {
|
|
25
|
-
return router.serverSsr.injectHtml(async () => {
|
|
26
|
-
const script = await getScript();
|
|
27
|
-
return `<script class='tsr-once'>${script}${process.env.NODE_ENV === "development" && ((opts == null ? void 0 : opts.logScript) ?? true) ? `; console.info(\`Injected From Server:
|
|
28
|
-
${jsesc(script, { quotes: "backtick" })}\`)` : ""}; if (typeof __TSR_SSR__ !== 'undefined') __TSR_SSR__.cleanScripts()<\/script>`;
|
|
29
|
-
});
|
|
30
|
-
},
|
|
31
|
-
streamValue: (key, value) => {
|
|
32
|
-
warning(
|
|
33
|
-
!router.serverSsr.streamedKeys.has(key),
|
|
34
|
-
"Key has already been streamed: " + key
|
|
35
|
-
);
|
|
36
|
-
router.serverSsr.streamedKeys.add(key);
|
|
37
|
-
router.serverSsr.injectScript(
|
|
38
|
-
() => `__TSR_SSR__.streamedValues['${key}'] = { value: ${jsesc(
|
|
39
|
-
router.ssr.serializer.stringify(value),
|
|
40
|
-
{
|
|
41
|
-
isScriptContext: true,
|
|
42
|
-
wrap: true,
|
|
43
|
-
json: true
|
|
44
|
-
}
|
|
45
|
-
)}}`
|
|
46
|
-
);
|
|
47
|
-
},
|
|
48
|
-
onMatchSettled
|
|
49
|
-
};
|
|
50
|
-
router.serverSsr.injectScript(() => minifiedTsrBootStrapScript, {
|
|
51
|
-
logScript: false
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
function dehydrateRouter(router) {
|
|
55
|
-
var _a, _b, _c;
|
|
56
|
-
const dehydratedRouter = {
|
|
57
|
-
manifest: router.ssr.manifest,
|
|
58
|
-
dehydratedData: (_b = (_a = router.options).dehydrate) == null ? void 0 : _b.call(_a),
|
|
59
|
-
lastMatchId: ((_c = router.state.matches[router.state.matches.length - 1]) == null ? void 0 : _c.id) || ""
|
|
60
|
-
};
|
|
61
|
-
router.serverSsr.injectScript(
|
|
62
|
-
() => `__TSR_SSR__.dehydrated = ${jsesc(
|
|
63
|
-
router.ssr.serializer.stringify(dehydratedRouter),
|
|
64
|
-
{
|
|
65
|
-
isScriptContext: true,
|
|
66
|
-
wrap: true,
|
|
67
|
-
json: true
|
|
68
|
-
}
|
|
69
|
-
)}`
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
function extractAsyncLoaderData(loaderData, ctx) {
|
|
73
|
-
const extracted = [];
|
|
74
|
-
const replaced = replaceBy(loaderData, (value, path) => {
|
|
75
|
-
if (value instanceof ReadableStream) {
|
|
76
|
-
const [copy1, copy2] = value.tee();
|
|
77
|
-
const entry = {
|
|
78
|
-
type: "stream",
|
|
79
|
-
path,
|
|
80
|
-
id: extracted.length,
|
|
81
|
-
matchIndex: ctx.match.index,
|
|
82
|
-
stream: copy2
|
|
83
|
-
};
|
|
84
|
-
extracted.push(entry);
|
|
85
|
-
return copy1;
|
|
86
|
-
} else if (value instanceof Promise) {
|
|
87
|
-
const deferredPromise = defer(value);
|
|
88
|
-
const entry = {
|
|
89
|
-
type: "promise",
|
|
90
|
-
path,
|
|
91
|
-
id: extracted.length,
|
|
92
|
-
matchIndex: ctx.match.index,
|
|
93
|
-
promise: deferredPromise
|
|
94
|
-
};
|
|
95
|
-
extracted.push(entry);
|
|
96
|
-
}
|
|
97
|
-
return value;
|
|
98
|
-
});
|
|
99
|
-
return { replaced, extracted };
|
|
100
|
-
}
|
|
101
|
-
function onMatchSettled(opts) {
|
|
102
|
-
const { router, match } = opts;
|
|
103
|
-
let extracted = void 0;
|
|
104
|
-
let serializedLoaderData = void 0;
|
|
105
|
-
if (match.loaderData !== void 0) {
|
|
106
|
-
const result = extractAsyncLoaderData(match.loaderData, {
|
|
107
|
-
match
|
|
108
|
-
});
|
|
109
|
-
match.loaderData = result.replaced;
|
|
110
|
-
extracted = result.extracted;
|
|
111
|
-
serializedLoaderData = extracted.reduce(
|
|
112
|
-
(acc, entry) => {
|
|
113
|
-
return deepImmutableSetByPath(acc, ["temp", ...entry.path], void 0);
|
|
114
|
-
},
|
|
115
|
-
{ temp: result.replaced }
|
|
116
|
-
).temp;
|
|
117
|
-
}
|
|
118
|
-
const initCode = `__TSR_SSR__.initMatch(${jsesc(
|
|
119
|
-
{
|
|
120
|
-
id: match.id,
|
|
121
|
-
__beforeLoadContext: router.ssr.serializer.stringify(
|
|
122
|
-
match.__beforeLoadContext
|
|
123
|
-
),
|
|
124
|
-
loaderData: router.ssr.serializer.stringify(serializedLoaderData),
|
|
125
|
-
error: router.ssr.serializer.stringify(match.error),
|
|
126
|
-
extracted: extracted == null ? void 0 : extracted.map((entry) => pick(entry, ["type", "path"])),
|
|
127
|
-
updatedAt: match.updatedAt,
|
|
128
|
-
status: match.status
|
|
129
|
-
},
|
|
130
|
-
{
|
|
131
|
-
isScriptContext: true,
|
|
132
|
-
wrap: true,
|
|
133
|
-
json: true
|
|
134
|
-
}
|
|
135
|
-
)})`;
|
|
136
|
-
router.serverSsr.injectScript(() => initCode);
|
|
137
|
-
if (extracted) {
|
|
138
|
-
extracted.forEach((entry) => {
|
|
139
|
-
if (entry.type === "promise") return injectPromise(entry);
|
|
140
|
-
return injectStream(entry);
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
function injectPromise(entry) {
|
|
144
|
-
router.serverSsr.injectScript(async () => {
|
|
145
|
-
await entry.promise;
|
|
146
|
-
return `__TSR_SSR__.resolvePromise(${jsesc(
|
|
147
|
-
{
|
|
148
|
-
matchId: match.id,
|
|
149
|
-
id: entry.id,
|
|
150
|
-
promiseState: entry.promise[TSR_DEFERRED_PROMISE]
|
|
151
|
-
},
|
|
152
|
-
{
|
|
153
|
-
isScriptContext: true,
|
|
154
|
-
wrap: true,
|
|
155
|
-
json: true
|
|
156
|
-
}
|
|
157
|
-
)})`;
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
function injectStream(entry) {
|
|
161
|
-
router.serverSsr.injectHtml(async () => {
|
|
162
|
-
try {
|
|
163
|
-
const reader = entry.stream.getReader();
|
|
164
|
-
let chunk = null;
|
|
165
|
-
while (!(chunk = await reader.read()).done) {
|
|
166
|
-
if (chunk.value) {
|
|
167
|
-
const code = `__TSR_SSR__.injectChunk(${jsesc(
|
|
168
|
-
{
|
|
169
|
-
matchId: match.id,
|
|
170
|
-
id: entry.id,
|
|
171
|
-
chunk: chunk.value
|
|
172
|
-
},
|
|
173
|
-
{
|
|
174
|
-
isScriptContext: true,
|
|
175
|
-
wrap: true,
|
|
176
|
-
json: true
|
|
177
|
-
}
|
|
178
|
-
)})`;
|
|
179
|
-
router.serverSsr.injectScript(() => code);
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
router.serverSsr.injectScript(
|
|
183
|
-
() => `__TSR_SSR__.closeStream(${jsesc(
|
|
184
|
-
{
|
|
185
|
-
matchId: match.id,
|
|
186
|
-
id: entry.id
|
|
187
|
-
},
|
|
188
|
-
{
|
|
189
|
-
isScriptContext: true,
|
|
190
|
-
wrap: true,
|
|
191
|
-
json: true
|
|
192
|
-
}
|
|
193
|
-
)})`
|
|
194
|
-
);
|
|
195
|
-
} catch (err) {
|
|
196
|
-
console.error("stream read error", err);
|
|
197
|
-
}
|
|
198
|
-
return "";
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
function deepImmutableSetByPath(obj, path, value) {
|
|
203
|
-
if (path.length === 0) {
|
|
204
|
-
return value;
|
|
205
|
-
}
|
|
206
|
-
const [key, ...rest] = path;
|
|
207
|
-
if (Array.isArray(obj)) {
|
|
208
|
-
return obj.map((item, i) => {
|
|
209
|
-
if (i === Number(key)) {
|
|
210
|
-
return deepImmutableSetByPath(item, rest, value);
|
|
211
|
-
}
|
|
212
|
-
return item;
|
|
213
|
-
});
|
|
214
|
-
}
|
|
215
|
-
if (isPlainObject(obj)) {
|
|
216
|
-
return {
|
|
217
|
-
...obj,
|
|
218
|
-
[key]: deepImmutableSetByPath(obj[key], rest, value)
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
return obj;
|
|
222
|
-
}
|
|
223
|
-
function replaceBy(obj, cb, path = []) {
|
|
224
|
-
if (isPlainArray(obj)) {
|
|
225
|
-
return obj.map((value, i) => replaceBy(value, cb, [...path, `${i}`]));
|
|
226
|
-
}
|
|
227
|
-
if (isPlainObject(obj)) {
|
|
228
|
-
const newObj2 = {};
|
|
229
|
-
for (const key in obj) {
|
|
230
|
-
newObj2[key] = replaceBy(obj[key], cb, [...path, key]);
|
|
231
|
-
}
|
|
232
|
-
return newObj2;
|
|
233
|
-
}
|
|
234
|
-
const newObj = cb(obj, path);
|
|
235
|
-
if (newObj !== obj) {
|
|
236
|
-
return newObj;
|
|
237
|
-
}
|
|
238
|
-
return obj;
|
|
239
|
-
}
|
|
240
|
-
export {
|
|
241
|
-
attachRouterServerSsrUtils,
|
|
242
|
-
dehydrateRouter,
|
|
243
|
-
extractAsyncLoaderData,
|
|
244
|
-
onMatchSettled,
|
|
245
|
-
replaceBy
|
|
246
|
-
};
|
|
247
|
-
//# sourceMappingURL=ssr-server.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ssr-server.js","sources":["../../src/ssr-server.ts"],"sourcesContent":["import { default as warning } from 'tiny-warning'\nimport {\n TSR_DEFERRED_PROMISE,\n defer,\n isPlainArray,\n isPlainObject,\n pick,\n} from '@tanstack/router-core'\nimport jsesc from 'jsesc'\nimport { startSerializer } from '@tanstack/start-client-core'\nimport minifiedTsrBootStrapScript from './tsrScript?script-string'\nimport type {\n ClientExtractedBaseEntry,\n DehydratedRouter,\n ResolvePromiseState,\n SsrMatch,\n} from '@tanstack/start-client-core'\nimport type {\n AnyRouteMatch,\n AnyRouter,\n DeferredPromise,\n Manifest,\n} from '@tanstack/router-core'\n\nexport type ServerExtractedEntry =\n | ServerExtractedStream\n | ServerExtractedPromise\n\nexport interface ServerExtractedBaseEntry extends ClientExtractedBaseEntry {\n id: number\n matchIndex: number\n}\n\nexport interface ServerExtractedStream extends ServerExtractedBaseEntry {\n type: 'stream'\n stream: ReadableStream\n}\n\nexport interface ServerExtractedPromise extends ServerExtractedBaseEntry {\n type: 'promise'\n promise: DeferredPromise<any>\n}\n\nexport function attachRouterServerSsrUtils(\n router: AnyRouter,\n manifest: Manifest | undefined,\n) {\n router.ssr = {\n manifest,\n serializer: startSerializer,\n }\n\n router.serverSsr = {\n injectedHtml: [],\n streamedKeys: new Set(),\n injectHtml: (getHtml) => {\n const promise = Promise.resolve().then(getHtml)\n router.serverSsr!.injectedHtml.push(promise)\n router.emit({\n type: 'onInjectedHtml',\n promise,\n })\n\n return promise.then(() => {})\n },\n injectScript: (getScript, opts) => {\n return router.serverSsr!.injectHtml(async () => {\n const script = await getScript()\n return `<script class='tsr-once'>${script}${\n process.env.NODE_ENV === 'development' && (opts?.logScript ?? true)\n ? `; console.info(\\`Injected From Server:\n${jsesc(script, { quotes: 'backtick' })}\\`)`\n : ''\n }; if (typeof __TSR_SSR__ !== 'undefined') __TSR_SSR__.cleanScripts()</script>`\n })\n },\n streamValue: (key, value) => {\n warning(\n !router.serverSsr!.streamedKeys.has(key),\n 'Key has already been streamed: ' + key,\n )\n\n router.serverSsr!.streamedKeys.add(key)\n router.serverSsr!.injectScript(\n () =>\n `__TSR_SSR__.streamedValues['${key}'] = { value: ${jsesc(\n router.ssr!.serializer.stringify(value),\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )}}`,\n )\n },\n onMatchSettled,\n }\n\n router.serverSsr.injectScript(() => minifiedTsrBootStrapScript, {\n logScript: false,\n })\n}\n\nexport function dehydrateRouter(router: AnyRouter) {\n const dehydratedRouter: DehydratedRouter = {\n manifest: router.ssr!.manifest,\n dehydratedData: router.options.dehydrate?.(),\n lastMatchId:\n router.state.matches[router.state.matches.length - 1]?.id || '',\n }\n\n router.serverSsr!.injectScript(\n () =>\n `__TSR_SSR__.dehydrated = ${jsesc(\n router.ssr!.serializer.stringify(dehydratedRouter),\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )}`,\n )\n}\n\nexport function extractAsyncLoaderData(\n loaderData: any,\n ctx: {\n match: AnyRouteMatch\n router: AnyRouter\n },\n) {\n const extracted: Array<ServerExtractedEntry> = []\n\n const replaced = replaceBy(loaderData, (value, path) => {\n // If it's a stream, we need to tee it so we can read it multiple times\n if (value instanceof ReadableStream) {\n const [copy1, copy2] = value.tee()\n const entry: ServerExtractedStream = {\n type: 'stream',\n path,\n id: extracted.length,\n matchIndex: ctx.match.index,\n stream: copy2,\n }\n\n extracted.push(entry)\n return copy1\n } else if (value instanceof Promise) {\n const deferredPromise = defer(value)\n const entry: ServerExtractedPromise = {\n type: 'promise',\n path,\n id: extracted.length,\n matchIndex: ctx.match.index,\n promise: deferredPromise,\n }\n extracted.push(entry)\n }\n\n return value\n })\n\n return { replaced, extracted }\n}\n\nexport function onMatchSettled(opts: {\n router: AnyRouter\n match: AnyRouteMatch\n}) {\n const { router, match } = opts\n\n let extracted: Array<ServerExtractedEntry> | undefined = undefined\n let serializedLoaderData: any = undefined\n if (match.loaderData !== undefined) {\n const result = extractAsyncLoaderData(match.loaderData, {\n router,\n match,\n })\n match.loaderData = result.replaced\n extracted = result.extracted\n serializedLoaderData = extracted.reduce(\n (acc: any, entry: ServerExtractedEntry) => {\n return deepImmutableSetByPath(acc, ['temp', ...entry.path], undefined)\n },\n { temp: result.replaced },\n ).temp\n }\n\n const initCode = `__TSR_SSR__.initMatch(${jsesc(\n {\n id: match.id,\n __beforeLoadContext: router.ssr!.serializer.stringify(\n match.__beforeLoadContext,\n ),\n loaderData: router.ssr!.serializer.stringify(serializedLoaderData),\n error: router.ssr!.serializer.stringify(match.error),\n extracted: extracted?.map((entry) => pick(entry, ['type', 'path'])),\n updatedAt: match.updatedAt,\n status: match.status,\n } satisfies SsrMatch,\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`\n\n router.serverSsr!.injectScript(() => initCode)\n\n if (extracted) {\n extracted.forEach((entry) => {\n if (entry.type === 'promise') return injectPromise(entry)\n return injectStream(entry)\n })\n }\n\n function injectPromise(entry: ServerExtractedPromise) {\n router.serverSsr!.injectScript(async () => {\n await entry.promise\n\n return `__TSR_SSR__.resolvePromise(${jsesc(\n {\n matchId: match.id,\n id: entry.id,\n promiseState: entry.promise[TSR_DEFERRED_PROMISE],\n } satisfies ResolvePromiseState,\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`\n })\n }\n\n function injectStream(entry: ServerExtractedStream) {\n // Inject a promise that resolves when the stream is done\n // We do this to keep the stream open until we're done\n router.serverSsr!.injectHtml(async () => {\n //\n try {\n const reader = entry.stream.getReader()\n let chunk: ReadableStreamReadResult<any> | null = null\n while (!(chunk = await reader.read()).done) {\n if (chunk.value) {\n const code = `__TSR_SSR__.injectChunk(${jsesc(\n {\n matchId: match.id,\n id: entry.id,\n chunk: chunk.value,\n },\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`\n\n router.serverSsr!.injectScript(() => code)\n }\n }\n\n router.serverSsr!.injectScript(\n () =>\n `__TSR_SSR__.closeStream(${jsesc(\n {\n matchId: match.id,\n id: entry.id,\n },\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`,\n )\n } catch (err) {\n console.error('stream read error', err)\n }\n\n return ''\n })\n }\n}\n\nfunction deepImmutableSetByPath<T>(obj: T, path: Array<string>, value: any): T {\n // immutable set by path retaining array and object references\n if (path.length === 0) {\n return value\n }\n\n const [key, ...rest] = path\n\n if (Array.isArray(obj)) {\n return obj.map((item, i) => {\n if (i === Number(key)) {\n return deepImmutableSetByPath(item, rest, value)\n }\n return item\n }) as T\n }\n\n if (isPlainObject(obj)) {\n return {\n ...obj,\n [key!]: deepImmutableSetByPath((obj as any)[key!], rest, value),\n }\n }\n\n return obj\n}\n\nexport function replaceBy<T>(\n obj: T,\n cb: (value: any, path: Array<string>) => any,\n path: Array<string> = [],\n): T {\n if (isPlainArray(obj)) {\n return obj.map((value, i) => replaceBy(value, cb, [...path, `${i}`])) as any\n }\n\n if (isPlainObject(obj)) {\n // Do not allow objects with illegal\n const newObj: any = {}\n\n for (const key in obj) {\n newObj[key] = replaceBy(obj[key], cb, [...path, key])\n }\n\n return newObj\n }\n\n // // Detect classes, functions, and other non-serializable objects\n // // and return undefined. Exclude some known types that are serializable\n // if (\n // typeof obj === 'function' ||\n // (typeof obj === 'object' &&\n // ![Object, Promise, ReadableStream].includes((obj as any)?.constructor))\n // ) {\n // console.info(obj)\n // warning(false, `Non-serializable value ☝️ found at ${path.join('.')}`)\n // return undefined as any\n // }\n\n const newObj = cb(obj, path)\n\n if (newObj !== obj) {\n return newObj\n }\n\n return obj\n}\n"],"names":["newObj"],"mappings":";;;;;AA2CgB,SAAA,2BACd,QACA,UACA;AACA,SAAO,MAAM;AAAA,IACX;AAAA,IACA,YAAY;AAAA,EACd;AAEA,SAAO,YAAY;AAAA,IACjB,cAAc,CAAC;AAAA,IACf,kCAAkB,IAAI;AAAA,IACtB,YAAY,CAAC,YAAY;AACvB,YAAM,UAAU,QAAQ,QAAQ,EAAE,KAAK,OAAO;AACvC,aAAA,UAAW,aAAa,KAAK,OAAO;AAC3C,aAAO,KAAK;AAAA,QACV,MAAM;AAAA,QACN;AAAA,MAAA,CACD;AAEM,aAAA,QAAQ,KAAK,MAAM;AAAA,MAAA,CAAE;AAAA,IAC9B;AAAA,IACA,cAAc,CAAC,WAAW,SAAS;AAC1B,aAAA,OAAO,UAAW,WAAW,YAAY;AACxC,cAAA,SAAS,MAAM,UAAU;AACxB,eAAA,4BAA4B,MAAM,GACvC,QAAQ,IAAI,aAAa,mBAAkB,6BAAM,cAAa,QAC1D;AAAA,EACZ,MAAM,QAAQ,EAAE,QAAQ,WAAY,CAAA,CAAC,QACzB,EACN;AAAA,MAAA,CACD;AAAA,IACH;AAAA,IACA,aAAa,CAAC,KAAK,UAAU;AAC3B;AAAA,QACE,CAAC,OAAO,UAAW,aAAa,IAAI,GAAG;AAAA,QACvC,oCAAoC;AAAA,MACtC;AAEO,aAAA,UAAW,aAAa,IAAI,GAAG;AACtC,aAAO,UAAW;AAAA,QAChB,MACE,+BAA+B,GAAG,iBAAiB;AAAA,UACjD,OAAO,IAAK,WAAW,UAAU,KAAK;AAAA,UACtC;AAAA,YACE,iBAAiB;AAAA,YACjB,MAAM;AAAA,YACN,MAAM;AAAA,UAAA;AAAA,QACR,CACD;AAAA,MACL;AAAA,IACF;AAAA,IACA;AAAA,EAC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;AAE1C,aAAA;AAAA,IAAA,CACR;AAAA,EAAA;AAGC,MAAA,cAAc,GAAG,GAAG;AACf,WAAA;AAAA,MACL,GAAG;AAAA,MACH,CAAC,GAAI,GAAG,uBAAwB,IAAY,GAAI,GAAG,MAAM,KAAK;AAAA,IAChE;AAAA,EAAA;AAGK,SAAA;AACT;AAEO,SAAS,UACd,KACA,IACA,OAAsB,CAAA,GACnB;AACC,MAAA,aAAa,GAAG,GAAG;AACrB,WAAO,IAAI,IAAI,CAAC,OAAO,MAAM,UAAU,OAAO,IAAI,CAAC,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,CAAC;AAAA,EAAA;AAGlE,MAAA,cAAc,GAAG,GAAG;AAEtB,UAAMA,UAAc,CAAC;AAErB,eAAW,OAAO,KAAK;AACrBA,cAAO,GAAG,IAAI,UAAU,IAAI,GAAG,GAAG,IAAI,CAAC,GAAG,MAAM,GAAG,CAAC;AAAA,IAAA;AAG/CA,WAAAA;AAAAA,EAAA;AAeH,QAAA,SAAS,GAAG,KAAK,IAAI;AAE3B,MAAI,WAAW,KAAK;AACX,WAAA;AAAA,EAAA;AAGF,SAAA;AACT;"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { ReadableStream } from 'node:stream/web';
|
|
2
|
-
import { Readable } from 'node:stream';
|
|
3
|
-
import { AnyRouter } from '@tanstack/router-core';
|
|
4
|
-
export declare function transformReadableStreamWithRouter(router: AnyRouter, routerStream: ReadableStream): ReadableStream<any>;
|
|
5
|
-
export declare function transformPipeableStreamWithRouter(router: AnyRouter, routerStream: Readable): Readable;
|
|
6
|
-
export declare function transformStreamWithRouter(router: AnyRouter, appStream: ReadableStream): ReadableStream<any>;
|
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
import { ReadableStream } from "node:stream/web";
|
|
2
|
-
import { Readable } from "node:stream";
|
|
3
|
-
import { createControlledPromise } from "@tanstack/router-core";
|
|
4
|
-
function transformReadableStreamWithRouter(router, routerStream) {
|
|
5
|
-
return transformStreamWithRouter(router, routerStream);
|
|
6
|
-
}
|
|
7
|
-
function transformPipeableStreamWithRouter(router, routerStream) {
|
|
8
|
-
return Readable.fromWeb(
|
|
9
|
-
transformStreamWithRouter(router, Readable.toWeb(routerStream))
|
|
10
|
-
);
|
|
11
|
-
}
|
|
12
|
-
const patternBodyStart = /(<body)/;
|
|
13
|
-
const patternBodyEnd = /(<\/body>)/;
|
|
14
|
-
const patternHtmlEnd = /(<\/html>)/;
|
|
15
|
-
const patternHeadStart = /(<head.*?>)/;
|
|
16
|
-
const patternClosingTag = /(<\/[a-zA-Z][\w:.-]*?>)/g;
|
|
17
|
-
const textDecoder = new TextDecoder();
|
|
18
|
-
function createPassthrough() {
|
|
19
|
-
let controller;
|
|
20
|
-
const encoder = new TextEncoder();
|
|
21
|
-
const stream = new ReadableStream({
|
|
22
|
-
start(c) {
|
|
23
|
-
controller = c;
|
|
24
|
-
}
|
|
25
|
-
});
|
|
26
|
-
const res = {
|
|
27
|
-
stream,
|
|
28
|
-
write: (chunk) => {
|
|
29
|
-
controller.enqueue(encoder.encode(chunk));
|
|
30
|
-
},
|
|
31
|
-
end: (chunk) => {
|
|
32
|
-
if (chunk) {
|
|
33
|
-
controller.enqueue(encoder.encode(chunk));
|
|
34
|
-
}
|
|
35
|
-
controller.close();
|
|
36
|
-
res.destroyed = true;
|
|
37
|
-
},
|
|
38
|
-
destroy: (error) => {
|
|
39
|
-
controller.error(error);
|
|
40
|
-
},
|
|
41
|
-
destroyed: false
|
|
42
|
-
};
|
|
43
|
-
return res;
|
|
44
|
-
}
|
|
45
|
-
async function readStream(stream, opts) {
|
|
46
|
-
var _a, _b, _c;
|
|
47
|
-
try {
|
|
48
|
-
const reader = stream.getReader();
|
|
49
|
-
let chunk;
|
|
50
|
-
while (!(chunk = await reader.read()).done) {
|
|
51
|
-
(_a = opts.onData) == null ? void 0 : _a.call(opts, chunk);
|
|
52
|
-
}
|
|
53
|
-
(_b = opts.onEnd) == null ? void 0 : _b.call(opts);
|
|
54
|
-
} catch (error) {
|
|
55
|
-
(_c = opts.onError) == null ? void 0 : _c.call(opts, error);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
function transformStreamWithRouter(router, appStream) {
|
|
59
|
-
const finalPassThrough = createPassthrough();
|
|
60
|
-
let isAppRendering = true;
|
|
61
|
-
let routerStreamBuffer = "";
|
|
62
|
-
let pendingClosingTags = "";
|
|
63
|
-
let bodyStarted = false;
|
|
64
|
-
let headStarted = false;
|
|
65
|
-
let leftover = "";
|
|
66
|
-
let leftoverHtml = "";
|
|
67
|
-
function getBufferedRouterStream() {
|
|
68
|
-
const html = routerStreamBuffer;
|
|
69
|
-
routerStreamBuffer = "";
|
|
70
|
-
return html;
|
|
71
|
-
}
|
|
72
|
-
function decodeChunk(chunk) {
|
|
73
|
-
if (chunk instanceof Uint8Array) {
|
|
74
|
-
return textDecoder.decode(chunk);
|
|
75
|
-
}
|
|
76
|
-
return String(chunk);
|
|
77
|
-
}
|
|
78
|
-
const injectedHtmlDonePromise = createControlledPromise();
|
|
79
|
-
let processingCount = 0;
|
|
80
|
-
router.serverSsr.injectedHtml.forEach((promise) => {
|
|
81
|
-
handleInjectedHtml(promise);
|
|
82
|
-
});
|
|
83
|
-
const stopListeningToInjectedHtml = router.subscribe(
|
|
84
|
-
"onInjectedHtml",
|
|
85
|
-
(e) => {
|
|
86
|
-
handleInjectedHtml(e.promise);
|
|
87
|
-
}
|
|
88
|
-
);
|
|
89
|
-
function handleInjectedHtml(promise) {
|
|
90
|
-
processingCount++;
|
|
91
|
-
promise.then((html) => {
|
|
92
|
-
if (!bodyStarted) {
|
|
93
|
-
routerStreamBuffer += html;
|
|
94
|
-
} else {
|
|
95
|
-
finalPassThrough.write(html);
|
|
96
|
-
}
|
|
97
|
-
}).catch(injectedHtmlDonePromise.reject).finally(() => {
|
|
98
|
-
processingCount--;
|
|
99
|
-
if (!isAppRendering && processingCount === 0) {
|
|
100
|
-
stopListeningToInjectedHtml();
|
|
101
|
-
injectedHtmlDonePromise.resolve();
|
|
102
|
-
}
|
|
103
|
-
});
|
|
104
|
-
}
|
|
105
|
-
injectedHtmlDonePromise.then(() => {
|
|
106
|
-
const finalHtml = leftoverHtml + getBufferedRouterStream() + pendingClosingTags;
|
|
107
|
-
finalPassThrough.end(finalHtml);
|
|
108
|
-
}).catch((err) => {
|
|
109
|
-
console.error("Error reading routerStream:", err);
|
|
110
|
-
finalPassThrough.destroy(err);
|
|
111
|
-
});
|
|
112
|
-
readStream(appStream, {
|
|
113
|
-
onData: (chunk) => {
|
|
114
|
-
const text = decodeChunk(chunk.value);
|
|
115
|
-
let chunkString = leftover + text;
|
|
116
|
-
const bodyEndMatch = chunkString.match(patternBodyEnd);
|
|
117
|
-
const htmlEndMatch = chunkString.match(patternHtmlEnd);
|
|
118
|
-
if (!bodyStarted) {
|
|
119
|
-
const bodyStartMatch = chunkString.match(patternBodyStart);
|
|
120
|
-
if (bodyStartMatch) {
|
|
121
|
-
bodyStarted = true;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
if (!headStarted) {
|
|
125
|
-
const headStartMatch = chunkString.match(patternHeadStart);
|
|
126
|
-
if (headStartMatch) {
|
|
127
|
-
headStarted = true;
|
|
128
|
-
const index = headStartMatch.index;
|
|
129
|
-
const headTag = headStartMatch[0];
|
|
130
|
-
const remaining = chunkString.slice(index + headTag.length);
|
|
131
|
-
finalPassThrough.write(
|
|
132
|
-
chunkString.slice(0, index) + headTag + getBufferedRouterStream()
|
|
133
|
-
);
|
|
134
|
-
chunkString = remaining;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
if (!bodyStarted) {
|
|
138
|
-
finalPassThrough.write(chunkString);
|
|
139
|
-
leftover = "";
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
if (bodyEndMatch && htmlEndMatch && bodyEndMatch.index < htmlEndMatch.index) {
|
|
143
|
-
const bodyEndIndex = bodyEndMatch.index;
|
|
144
|
-
pendingClosingTags = chunkString.slice(bodyEndIndex);
|
|
145
|
-
finalPassThrough.write(
|
|
146
|
-
chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream()
|
|
147
|
-
);
|
|
148
|
-
leftover = "";
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
151
|
-
let result;
|
|
152
|
-
let lastIndex = 0;
|
|
153
|
-
while ((result = patternClosingTag.exec(chunkString)) !== null) {
|
|
154
|
-
lastIndex = result.index + result[0].length;
|
|
155
|
-
}
|
|
156
|
-
if (lastIndex > 0) {
|
|
157
|
-
const processed = chunkString.slice(0, lastIndex) + getBufferedRouterStream() + leftoverHtml;
|
|
158
|
-
finalPassThrough.write(processed);
|
|
159
|
-
leftover = chunkString.slice(lastIndex);
|
|
160
|
-
} else {
|
|
161
|
-
leftover = chunkString;
|
|
162
|
-
leftoverHtml += getBufferedRouterStream();
|
|
163
|
-
}
|
|
164
|
-
},
|
|
165
|
-
onEnd: () => {
|
|
166
|
-
isAppRendering = false;
|
|
167
|
-
if (processingCount === 0) {
|
|
168
|
-
injectedHtmlDonePromise.resolve();
|
|
169
|
-
}
|
|
170
|
-
},
|
|
171
|
-
onError: (error) => {
|
|
172
|
-
console.error("Error reading appStream:", error);
|
|
173
|
-
finalPassThrough.destroy(error);
|
|
174
|
-
}
|
|
175
|
-
});
|
|
176
|
-
return finalPassThrough.stream;
|
|
177
|
-
}
|
|
178
|
-
export {
|
|
179
|
-
transformPipeableStreamWithRouter,
|
|
180
|
-
transformReadableStreamWithRouter,
|
|
181
|
-
transformStreamWithRouter
|
|
182
|
-
};
|
|
183
|
-
//# sourceMappingURL=transformStreamWithRouter.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"transformStreamWithRouter.js","sources":["../../src/transformStreamWithRouter.ts"],"sourcesContent":["import { ReadableStream } from 'node:stream/web'\nimport { Readable } from 'node:stream'\nimport { createControlledPromise } from '@tanstack/router-core'\nimport type { AnyRouter } from '@tanstack/router-core'\n\nexport function transformReadableStreamWithRouter(\n router: AnyRouter,\n routerStream: ReadableStream,\n) {\n return transformStreamWithRouter(router, routerStream)\n}\n\nexport function transformPipeableStreamWithRouter(\n router: AnyRouter,\n routerStream: Readable,\n) {\n return Readable.fromWeb(\n transformStreamWithRouter(router, Readable.toWeb(routerStream)),\n )\n}\n\n// regex pattern for matching closing body and html tags\nconst patternBodyStart = /(<body)/\nconst patternBodyEnd = /(<\\/body>)/\nconst patternHtmlEnd = /(<\\/html>)/\nconst patternHeadStart = /(<head.*?>)/\n// regex pattern for matching closing tags\nconst patternClosingTag = /(<\\/[a-zA-Z][\\w:.-]*?>)/g\n\nconst textDecoder = new TextDecoder()\n\ntype ReadablePassthrough = {\n stream: ReadableStream\n write: (chunk: string) => void\n end: (chunk?: string) => void\n destroy: (error: unknown) => void\n destroyed: boolean\n}\n\nfunction createPassthrough() {\n let controller: ReadableStreamDefaultController<any>\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(c) {\n controller = c\n },\n })\n\n const res: ReadablePassthrough = {\n stream,\n write: (chunk) => {\n controller.enqueue(encoder.encode(chunk))\n },\n end: (chunk) => {\n if (chunk) {\n controller.enqueue(encoder.encode(chunk))\n }\n controller.close()\n res.destroyed = true\n },\n destroy: (error) => {\n controller.error(error)\n },\n destroyed: false,\n }\n\n return res\n}\n\nasync function readStream(\n stream: ReadableStream,\n opts: {\n onData?: (chunk: ReadableStreamReadValueResult<any>) => void\n onEnd?: () => void\n onError?: (error: unknown) => void\n },\n) {\n try {\n const reader = stream.getReader()\n let chunk\n while (!(chunk = await reader.read()).done) {\n opts.onData?.(chunk)\n }\n opts.onEnd?.()\n } catch (error) {\n opts.onError?.(error)\n }\n}\n\nexport function transformStreamWithRouter(\n router: AnyRouter,\n appStream: ReadableStream,\n) {\n const finalPassThrough = createPassthrough()\n\n let isAppRendering = true as boolean\n let routerStreamBuffer = ''\n let pendingClosingTags = ''\n let bodyStarted = false as boolean\n let headStarted = false as boolean\n let leftover = ''\n let leftoverHtml = ''\n\n function getBufferedRouterStream() {\n const html = routerStreamBuffer\n routerStreamBuffer = ''\n return html\n }\n\n function decodeChunk(chunk: unknown): string {\n if (chunk instanceof Uint8Array) {\n return textDecoder.decode(chunk)\n }\n return String(chunk)\n }\n\n const injectedHtmlDonePromise = createControlledPromise<void>()\n\n let processingCount = 0\n\n // Process any already-injected HTML\n router.serverSsr!.injectedHtml.forEach((promise) => {\n handleInjectedHtml(promise)\n })\n\n // Listen for any new injected HTML\n const stopListeningToInjectedHtml = router.subscribe(\n 'onInjectedHtml',\n (e) => {\n handleInjectedHtml(e.promise)\n },\n )\n\n function handleInjectedHtml(promise: Promise<string>) {\n processingCount++\n\n promise\n .then((html) => {\n if (!bodyStarted) {\n routerStreamBuffer += html\n } else {\n finalPassThrough.write(html)\n }\n })\n .catch(injectedHtmlDonePromise.reject)\n .finally(() => {\n processingCount--\n\n if (!isAppRendering && processingCount === 0) {\n stopListeningToInjectedHtml()\n injectedHtmlDonePromise.resolve()\n }\n })\n }\n\n injectedHtmlDonePromise\n .then(() => {\n const finalHtml =\n leftoverHtml + getBufferedRouterStream() + pendingClosingTags\n\n finalPassThrough.end(finalHtml)\n })\n .catch((err) => {\n console.error('Error reading routerStream:', err)\n finalPassThrough.destroy(err)\n })\n\n // Transform the appStream\n readStream(appStream, {\n onData: (chunk) => {\n const text = decodeChunk(chunk.value)\n\n let chunkString = leftover + text\n const bodyEndMatch = chunkString.match(patternBodyEnd)\n const htmlEndMatch = chunkString.match(patternHtmlEnd)\n\n if (!bodyStarted) {\n const bodyStartMatch = chunkString.match(patternBodyStart)\n if (bodyStartMatch) {\n bodyStarted = true\n }\n }\n\n if (!headStarted) {\n const headStartMatch = chunkString.match(patternHeadStart)\n if (headStartMatch) {\n headStarted = true\n const index = headStartMatch.index!\n const headTag = headStartMatch[0]\n const remaining = chunkString.slice(index + headTag.length)\n finalPassThrough.write(\n chunkString.slice(0, index) + headTag + getBufferedRouterStream(),\n )\n // make sure to only write `remaining` until the next closing tag\n chunkString = remaining\n }\n }\n\n if (!bodyStarted) {\n finalPassThrough.write(chunkString)\n leftover = ''\n return\n }\n\n // If either the body end or html end is in the chunk,\n // We need to get all of our data in asap\n if (\n bodyEndMatch &&\n htmlEndMatch &&\n bodyEndMatch.index! < htmlEndMatch.index!\n ) {\n const bodyEndIndex = bodyEndMatch.index!\n pendingClosingTags = chunkString.slice(bodyEndIndex)\n\n finalPassThrough.write(\n chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream(),\n )\n\n leftover = ''\n return\n }\n\n let result: RegExpExecArray | null\n let lastIndex = 0\n while ((result = patternClosingTag.exec(chunkString)) !== null) {\n lastIndex = result.index + result[0].length\n }\n\n if (lastIndex > 0) {\n const processed =\n chunkString.slice(0, lastIndex) +\n getBufferedRouterStream() +\n leftoverHtml\n\n finalPassThrough.write(processed)\n leftover = chunkString.slice(lastIndex)\n } else {\n leftover = chunkString\n leftoverHtml += getBufferedRouterStream()\n }\n },\n onEnd: () => {\n // Mark the app as done rendering\n isAppRendering = false\n\n // If there are no pending promises, resolve the injectedHtmlDonePromise\n if (processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n }\n },\n onError: (error) => {\n console.error('Error reading appStream:', error)\n finalPassThrough.destroy(error)\n },\n })\n\n return finalPassThrough.stream\n}\n"],"names":[],"mappings":";;;AAKgB,SAAA,kCACd,QACA,cACA;AACO,SAAA,0BAA0B,QAAQ,YAAY;AACvD;AAEgB,SAAA,kCACd,QACA,cACA;AACA,SAAO,SAAS;AAAA,IACd,0BAA0B,QAAQ,SAAS,MAAM,YAAY,CAAC;AAAA,EAChE;AACF;AAGA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AAEzB,MAAM,oBAAoB;AAE1B,MAAM,cAAc,IAAI,YAAY;AAUpC,SAAS,oBAAoB;AACvB,MAAA;AACE,QAAA,UAAU,IAAI,YAAY;AAC1B,QAAA,SAAS,IAAI,eAAe;AAAA,IAChC,MAAM,GAA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AClE;AAEc,wBAAA;AAAA,QAAA;AAAA,MAChB;AAGF,UAAI,CAAC,aAAa;AAChB,yBAAiB,MAAM,WAAW;AACvB,mBAAA;AACX;AAAA,MAAA;AAKF,UACE,gBACA,gBACA,aAAa,QAAS,aAAa,OACnC;AACA,cAAM,eAAe,aAAa;AACb,6BAAA,YAAY,MAAM,YAAY;AAElC,yBAAA;AAAA,UACf,YAAY,MAAM,GAAG,YAAY,IAAI,wBAAwB;AAAA,QAC/D;AAEW,mBAAA;AACX;AAAA,MAAA;AAGE,UAAA;AACJ,UAAI,YAAY;AAChB,cAAQ,SAAS,kBAAkB,KAAK,WAAW,OAAO,MAAM;AAC9D,oBAAY,OAAO,QAAQ,OAAO,CAAC,EAAE;AAAA,MAAA;AAGvC,UAAI,YAAY,GAAG;AACjB,cAAM,YACJ,YAAY,MAAM,GAAG,SAAS,IAC9B,4BACA;AAEF,yBAAiB,MAAM,SAAS;AACrB,mBAAA,YAAY,MAAM,SAAS;AAAA,MAAA,OACjC;AACM,mBAAA;AACX,wBAAgB,wBAAwB;AAAA,MAAA;AAAA,IAE5C;AAAA,IACA,OAAO,MAAM;AAEM,uBAAA;AAGjB,UAAI,oBAAoB,GAAG;AACzB,gCAAwB,QAAQ;AAAA,MAAA;AAAA,IAEpC;AAAA,IACA,SAAS,CAAC,UAAU;AACV,cAAA,MAAM,4BAA4B,KAAK;AAC/C,uBAAiB,QAAQ,KAAK;AAAA,IAAA;AAAA,EAChC,CACD;AAED,SAAO,iBAAiB;AAC1B;"}
|
package/dist/esm/tsrScript.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/esm/tsrScript.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
const minifiedTsrBootStrapScript = 'const __TSR_SSR__={matches:[],streamedValues:{},initMatch:o=>(__TSR_SSR__.matches.push(o),o.extracted?.forEach(l=>{if(l.type==="stream"){let r;l.value=new ReadableStream({start(e){r={enqueue:t=>{try{e.enqueue(t)}catch{}},close:()=>{try{e.close()}catch{}}}}}),l.value.controller=r}else{let r,e;l.value=new Promise((t,a)=>{e=a,r=t}),l.value.reject=e,l.value.resolve=r}}),!0),resolvePromise:({matchId:o,id:l,promiseState:r})=>{const e=__TSR_SSR__.matches.find(t=>t.id===o);if(e){const t=e.extracted?.[l];if(t&&t.type==="promise"&&t.value&&r.status==="success")return t.value.resolve(r.data),!0}return!1},injectChunk:({matchId:o,id:l,chunk:r})=>{const e=__TSR_SSR__.matches.find(t=>t.id===o);if(e){const t=e.extracted?.[l];if(t&&t.type==="stream"&&t.value?.controller)return t.value.controller.enqueue(new TextEncoder().encode(r.toString())),!0}return!1},closeStream:({matchId:o,id:l})=>{const r=__TSR_SSR__.matches.find(e=>e.id===o);if(r){const e=r.extracted?.[l];if(e&&e.type==="stream"&&e.value?.controller)return e.value.controller.close(),!0}return!1},cleanScripts:()=>{document.querySelectorAll(".tsr-once").forEach(o=>{o.remove()})}};window.__TSR_SSR__=__TSR_SSR__;\n';
|
|
2
|
-
export {
|
|
3
|
-
minifiedTsrBootStrapScript as default
|
|
4
|
-
};
|
|
5
|
-
//# sourceMappingURL=tsrScript.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tsrScript.js","sources":["../../src/tsrScript.ts?script-string"],"sourcesContent":["import type { ControllablePromise } from '@tanstack/router-core'\nimport type { StartSsrGlobal } from '@tanstack/start-client-core'\n\nconst __TSR_SSR__: StartSsrGlobal = {\n matches: [],\n streamedValues: {},\n initMatch: (match) => {\n __TSR_SSR__.matches.push(match)\n\n match.extracted?.forEach((ex) => {\n if (ex.type === 'stream') {\n let controller\n ex.value = new ReadableStream({\n start(c) {\n controller = {\n enqueue: (chunk: unknown) => {\n try {\n c.enqueue(chunk)\n } catch {}\n },\n close: () => {\n try {\n c.close()\n } catch {}\n },\n }\n },\n })\n ex.value.controller = controller\n } else {\n let resolve: ControllablePromise['reject'] | undefined\n let reject: ControllablePromise['reject'] | undefined\n\n ex.value = new Promise((_resolve, _reject) => {\n reject = _reject\n resolve = _resolve\n }) as ControllablePromise\n ex.value.reject = reject!\n ex.value.resolve = resolve!\n }\n })\n\n return true\n },\n resolvePromise: ({ matchId, id, promiseState }) => {\n const match = __TSR_SSR__.matches.find((m) => m.id === matchId)\n if (match) {\n const ex = match.extracted?.[id]\n if (\n ex &&\n ex.type === 'promise' &&\n ex.value &&\n promiseState.status === 'success'\n ) {\n ex.value.resolve(promiseState.data)\n return true\n }\n }\n return false\n },\n injectChunk: ({ matchId, id, chunk }) => {\n const match = __TSR_SSR__.matches.find((m) => m.id === matchId)\n\n if (match) {\n const ex = match.extracted?.[id]\n if (ex && ex.type === 'stream' && ex.value?.controller) {\n ex.value.controller.enqueue(new TextEncoder().encode(chunk.toString()))\n return true\n }\n }\n return false\n },\n closeStream: ({ matchId, id }) => {\n const match = __TSR_SSR__.matches.find((m) => m.id === matchId)\n if (match) {\n const ex = match.extracted?.[id]\n if (ex && ex.type === 'stream' && ex.value?.controller) {\n ex.value.controller.close()\n return true\n }\n }\n return false\n },\n cleanScripts: () => {\n document.querySelectorAll('.tsr-once').forEach((el) => {\n el.remove()\n })\n },\n}\n\nwindow.__TSR_SSR__ = __TSR_SSR__\n"],"names":[],"mappings":"AAAA,MAAA,6BAAe;"}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
export declare const VIRTUAL_MODULES: {
|
|
2
|
-
readonly routeTree: "tanstack-start-route-tree:v";
|
|
3
|
-
readonly startManifest: "tanstack-start-manifest:v";
|
|
4
|
-
readonly serverFnManifest: "tanstack-start-server-fn-manifest:v";
|
|
5
|
-
};
|
|
6
|
-
export type VirtualModules = {
|
|
7
|
-
[VIRTUAL_MODULES.routeTree]: typeof import('tanstack-start-route-tree:v');
|
|
8
|
-
[VIRTUAL_MODULES.startManifest]: typeof import('tanstack-start-manifest:v');
|
|
9
|
-
[VIRTUAL_MODULES.serverFnManifest]: typeof import('tanstack-start-server-fn-manifest:v');
|
|
10
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"virtual-modules.js","sources":["../../src/virtual-modules.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/consistent-type-imports */\n\nexport const VIRTUAL_MODULES = {\n routeTree: 'tanstack-start-route-tree:v',\n startManifest: 'tanstack-start-manifest:v',\n serverFnManifest: 'tanstack-start-server-fn-manifest:v',\n} as const\n\nexport type VirtualModules = {\n [VIRTUAL_MODULES.routeTree]: typeof import('tanstack-start-route-tree:v')\n [VIRTUAL_MODULES.startManifest]: typeof import('tanstack-start-manifest:v')\n [VIRTUAL_MODULES.serverFnManifest]: typeof import('tanstack-start-server-fn-manifest:v')\n}\n"],"names":[],"mappings":"AAEO,MAAM,kBAAkB;AAAA,EAC7B,WAAW;AAAA,EACX,eAAe;AAAA,EACf,kBAAkB;AACpB;"}
|