@bleedingdev/modern-js-renderer-octane 0.0.0-stage → 3.9.3-ultramodern.1

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.
Files changed (138) hide show
  1. package/LICENSE +21 -0
  2. package/bin/octane-tsc.mjs +4 -0
  3. package/dist/cjs/bootstrap.js +68 -0
  4. package/dist/cjs/client.js +371 -0
  5. package/dist/cjs/entry-application.js +83 -0
  6. package/dist/cjs/entry-client.js +92 -0
  7. package/dist/cjs/entry-server.js +127 -0
  8. package/dist/cjs/federation-context.js +72 -0
  9. package/dist/cjs/federation.js +103 -0
  10. package/dist/cjs/i18n/I18nProvider.js +67 -0
  11. package/dist/cjs/i18n/LocalizedLink.js +89 -0
  12. package/dist/cjs/i18n/context.js +41 -0
  13. package/dist/cjs/i18n/index.js +86 -0
  14. package/dist/cjs/i18n/languageSync.js +99 -0
  15. package/dist/cjs/i18n/types.js +18 -0
  16. package/dist/cjs/i18n/useI18n.js +110 -0
  17. package/dist/cjs/index.js +46 -0
  18. package/dist/cjs/manifest.js +167 -0
  19. package/dist/cjs/plugin/compiler.js +125 -0
  20. package/dist/cjs/plugin/create.js +265 -0
  21. package/dist/cjs/plugin/index.js +151 -0
  22. package/dist/cjs/plugin/profile.js +89 -0
  23. package/dist/cjs/plugin/source.js +56 -0
  24. package/dist/cjs/router-client.js +139 -0
  25. package/dist/cjs/router-handler.js +168 -0
  26. package/dist/cjs/router-injection.js +139 -0
  27. package/dist/cjs/router-server-cleanup.js +46 -0
  28. package/dist/cjs/router-server-snapshot.js +405 -0
  29. package/dist/cjs/router-server.js +108 -0
  30. package/dist/cjs/router-snapshot.js +270 -0
  31. package/dist/cjs/router.js +218 -0
  32. package/dist/cjs/routes.js +187 -0
  33. package/dist/cjs/server.js +224 -0
  34. package/dist/cjs/typecheck.js +615 -0
  35. package/dist/esm/bootstrap.mjs +24 -0
  36. package/dist/esm/client.mjs +327 -0
  37. package/dist/esm/entry-application.mjs +39 -0
  38. package/dist/esm/entry-client.mjs +54 -0
  39. package/dist/esm/entry-server.mjs +86 -0
  40. package/dist/esm/federation-context.mjs +25 -0
  41. package/dist/esm/federation.mjs +65 -0
  42. package/dist/esm/i18n/I18nProvider.mjs +29 -0
  43. package/dist/esm/i18n/LocalizedLink.mjs +48 -0
  44. package/dist/esm/i18n/context.mjs +3 -0
  45. package/dist/esm/i18n/index.mjs +8 -0
  46. package/dist/esm/i18n/languageSync.mjs +61 -0
  47. package/dist/esm/i18n/types.mjs +0 -0
  48. package/dist/esm/i18n/useI18n.mjs +72 -0
  49. package/dist/esm/index.mjs +8 -0
  50. package/dist/esm/manifest.mjs +117 -0
  51. package/dist/esm/router-client.mjs +98 -0
  52. package/dist/esm/router-handler.mjs +130 -0
  53. package/dist/esm/router-injection.mjs +101 -0
  54. package/dist/esm/router-server-cleanup.mjs +8 -0
  55. package/dist/esm/router-server-snapshot.mjs +367 -0
  56. package/dist/esm/router-server.mjs +12 -0
  57. package/dist/esm/router-snapshot.mjs +199 -0
  58. package/dist/esm/router.mjs +94 -0
  59. package/dist/esm/routes.mjs +134 -0
  60. package/dist/esm/server.mjs +183 -0
  61. package/dist/esm-node/bootstrap.mjs +24 -0
  62. package/dist/esm-node/manifest.mjs +117 -0
  63. package/dist/esm-node/plugin/compiler.mjs +70 -0
  64. package/dist/esm-node/plugin/create.mjs +227 -0
  65. package/dist/esm-node/plugin/index.mjs +103 -0
  66. package/dist/esm-node/plugin/profile.mjs +51 -0
  67. package/dist/esm-node/plugin/source.mjs +7 -0
  68. package/dist/esm-node/typecheck.mjs +560 -0
  69. package/dist/types/bootstrap.d.ts +10 -0
  70. package/dist/types/client.d.ts +36 -0
  71. package/dist/types/entry-application.d.ts +19 -0
  72. package/dist/types/entry-client.d.ts +8 -0
  73. package/dist/types/entry-server.d.ts +11 -0
  74. package/dist/types/federation-context.d.ts +28 -0
  75. package/dist/types/federation.d.ts +18 -0
  76. package/dist/types/i18n/I18nProvider.d.ts +8 -0
  77. package/dist/types/i18n/LocalizedLink.d.ts +41 -0
  78. package/dist/types/i18n/context.d.ts +9 -0
  79. package/dist/types/i18n/index.d.ts +9 -0
  80. package/dist/types/i18n/languageSync.d.ts +26 -0
  81. package/dist/types/i18n/types.d.ts +34 -0
  82. package/dist/types/i18n/useI18n.d.ts +21 -0
  83. package/dist/types/index.d.ts +9 -0
  84. package/dist/types/manifest.d.ts +34 -0
  85. package/dist/types/plugin/compiler-manifest.d.cts +10 -0
  86. package/dist/types/plugin/compiler.d.ts +5 -0
  87. package/dist/types/plugin/create.d.ts +23 -0
  88. package/dist/types/plugin/index.d.ts +3 -0
  89. package/dist/types/plugin/profile.d.ts +2 -0
  90. package/dist/types/plugin/source.d.ts +1 -0
  91. package/dist/types/plugin/svg-component-template.d.cts +6 -0
  92. package/dist/types/router-client.d.ts +12 -0
  93. package/dist/types/router-handler.d.ts +13 -0
  94. package/dist/types/router-injection.d.ts +8 -0
  95. package/dist/types/router-server-cleanup.d.ts +3 -0
  96. package/dist/types/router-server-snapshot.d.ts +15 -0
  97. package/dist/types/router-server.d.ts +13 -0
  98. package/dist/types/router-snapshot.d.ts +14 -0
  99. package/dist/types/router.d.ts +30 -0
  100. package/dist/types/routes.d.ts +18 -0
  101. package/dist/types/server.d.ts +41 -0
  102. package/dist/types/typecheck.d.ts +31 -0
  103. package/package.json +216 -4
  104. package/src/bootstrap.ts +60 -0
  105. package/src/client.ts +485 -0
  106. package/src/entry-application.ts +72 -0
  107. package/src/entry-client.ts +80 -0
  108. package/src/entry-server.ts +142 -0
  109. package/src/federation-context.ts +53 -0
  110. package/src/federation.ts +158 -0
  111. package/src/i18n/I18nProvider.ts +56 -0
  112. package/src/i18n/LocalizedLink.ts +112 -0
  113. package/src/i18n/context.ts +12 -0
  114. package/src/i18n/index.ts +35 -0
  115. package/src/i18n/languageSync.ts +132 -0
  116. package/src/i18n/types.ts +36 -0
  117. package/src/i18n/useI18n.ts +119 -0
  118. package/src/index.ts +10 -0
  119. package/src/manifest.ts +253 -0
  120. package/src/plugin/compiler-manifest.cjs +178 -0
  121. package/src/plugin/compiler.ts +112 -0
  122. package/src/plugin/create.ts +272 -0
  123. package/src/plugin/index.ts +105 -0
  124. package/src/plugin/profile.ts +46 -0
  125. package/src/plugin/source.ts +16 -0
  126. package/src/plugin/svg-component-template.cjs +17 -0
  127. package/src/router-client.ts +144 -0
  128. package/src/router-handler.ts +182 -0
  129. package/src/router-injection.ts +145 -0
  130. package/src/router-server-cleanup.ts +11 -0
  131. package/src/router-server-snapshot.ts +564 -0
  132. package/src/router-server.ts +23 -0
  133. package/src/router-snapshot.ts +251 -0
  134. package/src/router.ts +192 -0
  135. package/src/routes.ts +263 -0
  136. package/src/server.ts +300 -0
  137. package/src/typecheck.ts +723 -0
  138. package/README.md +0 -3
@@ -0,0 +1,134 @@
1
+ import { RouteDataError, loadFileSystemRoute, matchApplicationRouteIds, matchApplicationRoutes, nativeRoutePath, resolveRouteData, selectApplicationDataRoute, splitFileSystemRoutes } from "@modern-js/renderer-core/router";
2
+ import { ErrorComponent, HeadContent, Outlet, Scripts, createRootRoute, createRoute, notFound, redirect } from "@octanejs/tanstack-router";
3
+ import { Fragment, createElement } from "octane";
4
+ function routes_resolveRouteData(routeId, outcome) {
5
+ return resolveRouteData({
6
+ redirect: redirect,
7
+ notFound: notFound
8
+ }, routeId, outcome);
9
+ }
10
+ function isReactiveNativeMatch(value) {
11
+ return 'object' == typeof value && null !== value && 'function' == typeof Reflect.get(value, 'get') && 'function' == typeof Reflect.get(value, 'subscribe');
12
+ }
13
+ function observeRouteCompletion(router, controller, signal, completion) {
14
+ completion.catch((error)=>{
15
+ if (signal.aborted) return;
16
+ const match = [
17
+ ...router.stores.pendingMatches.get(),
18
+ ...router.stores.matches.get(),
19
+ ...router.stores.cachedMatches.get()
20
+ ].find((candidate)=>candidate.abortController === controller);
21
+ if (!match) return;
22
+ const store = [
23
+ router.stores.pendingMatchStores.get(match.id),
24
+ router.stores.matchStores.get(match.id),
25
+ router.stores.cachedMatchStores.get(match.id)
26
+ ].find((candidate)=>candidate?.get().abortController === controller);
27
+ if (!store) return;
28
+ let subscription;
29
+ let settled = false;
30
+ const cleanup = ()=>{
31
+ subscription?.unsubscribe();
32
+ signal.removeEventListener('abort', onAbort);
33
+ };
34
+ const onAbort = ()=>{
35
+ settled = true;
36
+ cleanup();
37
+ };
38
+ const publish = ()=>{
39
+ if (settled) return;
40
+ const current = store.get();
41
+ if (current.abortController !== controller || signal.aborted || 'pending' !== current.status && 'success' !== current.status) return void onAbort();
42
+ if ('success' !== current.status || current.isFetching) return;
43
+ settled = true;
44
+ cleanup();
45
+ const route = router.routesById[current.routeId];
46
+ let failure = error;
47
+ try {
48
+ route?.options.onError?.(failure);
49
+ } catch (onErrorFailure) {
50
+ failure = onErrorFailure;
51
+ }
52
+ if (signal.aborted) return;
53
+ router.updateMatch(match.id, (previous)=>previous.abortController !== controller || 'success' !== previous.status || previous.isFetching ? previous : {
54
+ ...previous,
55
+ error: failure,
56
+ status: 'error',
57
+ isFetching: false
58
+ });
59
+ };
60
+ signal.addEventListener('abort', onAbort, {
61
+ once: true
62
+ });
63
+ if (isReactiveNativeMatch(store)) subscription = store.subscribe(publish);
64
+ if (settled) subscription?.unsubscribe();
65
+ else publish();
66
+ });
67
+ }
68
+ function createFileSystemRouteTree(routes, modules, options = {}) {
69
+ const { root: rootDescriptor, children } = splitFileSystemRoutes(routes);
70
+ function bindings(route, errorComponent) {
71
+ const needsData = Boolean(route.modules?.data || route.modules?.clientData);
72
+ if (needsData && !options.loadRoute) throw new Error(`An Octane data route requires its loader: ${route.id}`);
73
+ const loadRoute = options.loadRoute;
74
+ const { head, ...module } = modules[route.id] ?? {};
75
+ return {
76
+ ...module,
77
+ ...void 0 !== head ? {
78
+ head
79
+ } : {},
80
+ ...errorComponent ? {
81
+ errorComponent
82
+ } : {},
83
+ component: module.component ?? Outlet,
84
+ staticData: {
85
+ ultramodernRouteId: route.id
86
+ },
87
+ ...needsData && loadRoute ? {
88
+ loader: async (match)=>{
89
+ const { outcome, signal } = await loadFileSystemRoute(route, loadRoute, options, match);
90
+ if ('completion' in outcome && outcome.completion) {
91
+ const router = options.getRouter?.();
92
+ if (!router) throw new Error('An Octane streamed data route requires its native router');
93
+ let failed = false;
94
+ let failure;
95
+ outcome.completion.catch((error)=>{
96
+ failed = true;
97
+ failure = error;
98
+ });
99
+ await Promise.resolve();
100
+ signal.throwIfAborted();
101
+ if (failed) throw failure;
102
+ observeRouteCompletion(router, match.abortController, signal, outcome.completion);
103
+ }
104
+ options.onOutcome?.(route.id, outcome);
105
+ return routes_resolveRouteData(route.id, outcome);
106
+ }
107
+ } : {}
108
+ };
109
+ }
110
+ const rootBindings = rootDescriptor ? bindings(rootDescriptor) : {
111
+ component: Outlet
112
+ };
113
+ const authoredRoot = rootBindings.component;
114
+ function OctaneDocumentRoot(props) {
115
+ return createElement(Fragment, null, createElement(HeadContent), createElement(authoredRoot, props), createElement(Scripts));
116
+ }
117
+ if (void 0 !== authoredRoot.preload) OctaneDocumentRoot.preload = authoredRoot.preload;
118
+ const rootErrorComponent = rootDescriptor && modules[rootDescriptor.id]?.errorComponent || ErrorComponent;
119
+ const root = createRootRoute({
120
+ ...rootBindings,
121
+ component: OctaneDocumentRoot
122
+ });
123
+ function bind(route, parent, inheritedErrorComponent) {
124
+ const errorComponent = modules[route.id]?.errorComponent ?? inheritedErrorComponent;
125
+ const native = createRoute({
126
+ getParentRoute: ()=>parent,
127
+ ...nativeRoutePath(route),
128
+ ...bindings(route, errorComponent)
129
+ });
130
+ return native.addChildren(route.children.map((child)=>bind(child, native, errorComponent)));
131
+ }
132
+ return root.addChildren(children.map((route)=>bind(route, root, rootErrorComponent)));
133
+ }
134
+ export { RouteDataError, createFileSystemRouteTree, matchApplicationRouteIds, matchApplicationRoutes, routes_resolveRouteData as resolveRouteData, selectApplicationDataRoute };
@@ -0,0 +1,183 @@
1
+ import { prepareDocument } from "@modern-js/renderer-core/document";
2
+ import { untilAborted } from "@modern-js/renderer-core/session";
3
+ import { createElement, earlySignalBootstrapScript, renderToReadableStream } from "octane/server";
4
+ import { assertNativeHydrationBuildId, assertOctaneIdentity } from "./bootstrap.mjs";
5
+ import { FederationRoot, createFederationScope } from "./federation-context.mjs";
6
+ function prepareOctaneDocument(session, document, hydrating) {
7
+ assertOctaneIdentity(session.identity);
8
+ if ('node' !== session.platform.kind && 'worker' !== session.platform.kind) throw new Error('An Octane document requires a Node or worker request platform.');
9
+ assertNativeHydrationBuildId(document.nativeHydrationBuildId);
10
+ const nonce = document.nonce;
11
+ return prepareDocument({
12
+ identity: session.identity,
13
+ documentId: document.documentId,
14
+ hydrating,
15
+ nativeHydrationBuildId: document.nativeHydrationBuildId
16
+ }, {
17
+ rootId: document.rootId,
18
+ lang: document.lang,
19
+ nonce: {
20
+ script: nonce,
21
+ style: nonce
22
+ },
23
+ assets: document.assets,
24
+ inlineData: document.inlineData
25
+ });
26
+ }
27
+ async function resolveDocumentResponse(input) {
28
+ const { session } = input;
29
+ if (input.responsePolicy && input.resolveResponse) throw new Error('Choose one blocking Octane response policy resolver.');
30
+ if (input.resolveResponse) session.resolveResponse(await untilAborted(input.resolveResponse(session), session.signal));
31
+ else if (input.responsePolicy) session.resolveResponse(input.responsePolicy);
32
+ else if (!session.responsePolicy) session.resolveResponse({
33
+ kind: 'document',
34
+ status: 200,
35
+ headers: [
36
+ [
37
+ 'content-type',
38
+ 'text/html; charset=utf-8'
39
+ ]
40
+ ],
41
+ cache: {
42
+ mode: 'no-store'
43
+ }
44
+ });
45
+ }
46
+ async function renderOctaneCSRDocument(input) {
47
+ const { session } = input;
48
+ try {
49
+ const { rootId, lang, bootstrap, headAssets, entryScripts } = prepareOctaneDocument(session, input.document, false);
50
+ await resolveDocumentResponse(input);
51
+ if (session.responsePolicy?.kind === 'terminal') return session.respond(null);
52
+ session.startRendering();
53
+ const bytes = new TextEncoder().encode(`<!doctype html><html lang="${lang}"><head>${headAssets}</head><body><div id="${rootId}"></div>${bootstrap}${entryScripts}</body></html>`);
54
+ return session.respond(new ReadableStream({
55
+ start (controller) {
56
+ controller.enqueue(bytes);
57
+ controller.close();
58
+ }
59
+ }));
60
+ } catch (error) {
61
+ await session.fail(error);
62
+ throw error;
63
+ }
64
+ }
65
+ async function renderOctaneApplication(input) {
66
+ const { session, document } = input;
67
+ try {
68
+ const { rootId, lang, bootstrap, headAssets, entryScripts } = prepareOctaneDocument(session, document, true);
69
+ const earlyBootstrap = earlySignalBootstrapScript(void 0 === document.nonce ? {} : {
70
+ nonce: document.nonce
71
+ });
72
+ await resolveDocumentResponse(input);
73
+ if (session.responsePolicy?.kind === 'terminal') return session.respond(null);
74
+ session.startRendering();
75
+ let head = '';
76
+ const federation = input.federation ? createFederationScope(input.federation, true, document.nonce) : void 0;
77
+ const App = federation ? ()=>createElement(FederationRoot, {
78
+ scope: federation,
79
+ children: 'function' == typeof input.App ? createElement(input.App, input.props) : input.App
80
+ }) : input.App;
81
+ const nativeStream = await renderToReadableStream(App, input.props, {
82
+ signal: session.signal,
83
+ ...void 0 === document.nonce ? {} : {
84
+ nonce: document.nonce
85
+ },
86
+ earlySignalBootstrap: 'external',
87
+ ...void 0 === input.injection ? {} : {
88
+ injection: input.injection
89
+ },
90
+ streamedSignals: {
91
+ buildId: document.nativeHydrationBuildId,
92
+ documentId: document.documentId
93
+ },
94
+ headChannel: 'separate',
95
+ onHeadReady (value) {
96
+ head = value;
97
+ },
98
+ onError (error) {
99
+ if (session.signal.aborted) return;
100
+ session.markFallback();
101
+ console.error('Octane render error:', error);
102
+ }
103
+ });
104
+ const ready = nativeStream.allReady.then(()=>({
105
+ ok: true
106
+ }), (error)=>({
107
+ ok: false,
108
+ error
109
+ }));
110
+ const reader = nativeStream.getReader();
111
+ const encoder = new TextEncoder();
112
+ const prefix = encoder.encode(`<!doctype html><html lang="${lang}"><head>${head}${headAssets}</head><body>${earlyBootstrap}<div id="${rootId}">`);
113
+ const shellBootstrap = encoder.encode(`</div>${bootstrap}${entryScripts}`);
114
+ const suffix = encoder.encode('</body></html>');
115
+ let phase = 'prefix';
116
+ let released = false;
117
+ const release = ()=>{
118
+ if (released) return;
119
+ released = true;
120
+ reader.releaseLock();
121
+ };
122
+ let cancellation;
123
+ const cancelNative = (reason)=>{
124
+ if (cancellation) return cancellation;
125
+ if (released) return Promise.resolve();
126
+ cancellation = reader.cancel(reason).finally(release);
127
+ return cancellation;
128
+ };
129
+ const releaseNative = (reason)=>{
130
+ cancelNative(reason).catch(()=>{});
131
+ };
132
+ try {
133
+ session.registerCleanup(()=>releaseNative(session.signal.reason));
134
+ } catch (error) {
135
+ releaseNative(error);
136
+ throw error;
137
+ }
138
+ const body = new ReadableStream({
139
+ async pull (controller) {
140
+ try {
141
+ if ('prefix' === phase) {
142
+ phase = 'shell';
143
+ controller.enqueue(prefix);
144
+ return;
145
+ }
146
+ if ('bootstrap' === phase) {
147
+ phase = 'native';
148
+ controller.enqueue(shellBootstrap);
149
+ return;
150
+ }
151
+ const next = await reader.read();
152
+ if (!next.done) {
153
+ if ('shell' === phase) phase = 'bootstrap';
154
+ controller.enqueue(next.value);
155
+ return;
156
+ }
157
+ if ('shell' === phase) throw new Error('Octane ended before publishing its initial shell.');
158
+ const completion = await ready;
159
+ release();
160
+ if (!completion.ok) throw completion.error;
161
+ phase = 'done';
162
+ controller.enqueue(suffix);
163
+ controller.close();
164
+ } catch (error) {
165
+ phase = 'done';
166
+ releaseNative(error);
167
+ controller.error(error);
168
+ }
169
+ },
170
+ cancel (reason) {
171
+ phase = 'done';
172
+ releaseNative(reason);
173
+ }
174
+ }, {
175
+ highWaterMark: 0
176
+ });
177
+ return session.respond(body);
178
+ } catch (error) {
179
+ await session.fail(error);
180
+ throw error;
181
+ }
182
+ }
183
+ export { renderOctaneApplication, renderOctaneCSRDocument };
@@ -0,0 +1,24 @@
1
+ import { readDocumentBootstrap } from "@modern-js/renderer-core/document";
2
+ import { readRendererIdentity } from "@modern-js/renderer-core/identity";
3
+ function assertNativeHydrationBuildId(value) {
4
+ if ('string' != typeof value || 0 === value.trim().length) throw new Error('An Octane document requires its native client compilation identity.');
5
+ }
6
+ function assertOctaneIdentity(identity) {
7
+ readRendererIdentity(identity, identity);
8
+ if ('octane' !== identity.renderer) throw new Error('An Octane application requires an Octane renderer identity.');
9
+ }
10
+ function readOctaneDocumentBootstrap(document, expectedIdentity, expectedNativeHydrationBuildId) {
11
+ assertOctaneIdentity(expectedIdentity);
12
+ const { identity, documentId, hydrating, nativeHydrationBuildId } = readDocumentBootstrap(document, expectedIdentity, [
13
+ 'nativeHydrationBuildId'
14
+ ]);
15
+ assertNativeHydrationBuildId(nativeHydrationBuildId);
16
+ if (void 0 !== expectedNativeHydrationBuildId && nativeHydrationBuildId !== expectedNativeHydrationBuildId) throw new Error('Octane hydration bytes belong to a different native client compilation.');
17
+ return Object.freeze({
18
+ identity,
19
+ documentId,
20
+ hydrating,
21
+ nativeHydrationBuildId
22
+ });
23
+ }
24
+ export { assertNativeHydrationBuildId, assertOctaneIdentity, readOctaneDocumentBootstrap };
@@ -0,0 +1,117 @@
1
+ import { nativeModuleManifestFilename, readRendererIdentity } from "@modern-js/renderer-core/identity";
2
+ import { assertNativeHydrationBuildId, assertOctaneIdentity } from "./bootstrap.mjs";
3
+ const OCTANE_RUNTIME_VERSION = '0.7.1+ultramodern.1331985ea3b0';
4
+ const OCTANE_COMPILER_VERSION = '0.1.55';
5
+ function octaneModuleManifestFileName(entryName) {
6
+ return nativeModuleManifestFilename('octane', entryName);
7
+ }
8
+ function record(value, fields) {
9
+ if (!value || 'object' != typeof value || Array.isArray(value)) throw new Error('Malformed Octane compiler manifest object.');
10
+ if (Object.keys(value).some((key)=>!fields.includes(key))) throw new Error('Octane compiler manifest contains an unknown field.');
11
+ return value;
12
+ }
13
+ function digest(value) {
14
+ return 'string' == typeof value && /^[a-f\d]{64}$/u.test(value);
15
+ }
16
+ function nonempty(value) {
17
+ return 'string' == typeof value && value.trim().length > 0 && !value.includes('\0');
18
+ }
19
+ function assetPath(value) {
20
+ return nonempty(value) && value.endsWith('.js') && !value.startsWith('/') && !value.includes('\\') && !value.split('/').some((part)=>'..' === part || '.' === part || !part);
21
+ }
22
+ const validatedManifests = new WeakMap();
23
+ function validateOctaneModuleManifest(value, expectedIdentity, expectedNativeHydrationBuildId) {
24
+ assertOctaneIdentity(expectedIdentity);
25
+ const cached = value && 'object' == typeof value ? validatedManifests.get(value) : void 0;
26
+ const manifest = cached ?? readOctaneModuleManifest(value);
27
+ readRendererIdentity(manifest.rendererIdentity, expectedIdentity);
28
+ if (void 0 !== expectedNativeHydrationBuildId) {
29
+ assertNativeHydrationBuildId(expectedNativeHydrationBuildId);
30
+ if (manifest.nativeHydrationBuildId !== expectedNativeHydrationBuildId) throw new Error('Octane native hydration build differs from the compiled client.');
31
+ }
32
+ if (!cached) {
33
+ validatedManifests.set(value, manifest);
34
+ validatedManifests.set(manifest, manifest);
35
+ }
36
+ return manifest;
37
+ }
38
+ function readOctaneModuleManifest(value) {
39
+ const manifest = record(value, [
40
+ 'schemaVersion',
41
+ 'renderer',
42
+ 'runtimeVersion',
43
+ 'compilerVersion',
44
+ 'rendererIdentity',
45
+ 'nativeHydrationBuildId',
46
+ 'sourceModules',
47
+ 'assets'
48
+ ]);
49
+ if (1 !== manifest.schemaVersion || 'octane' !== manifest.renderer || manifest.runtimeVersion !== OCTANE_RUNTIME_VERSION || manifest.compilerVersion !== OCTANE_COMPILER_VERSION) throw new Error('Octane compiler manifest ABI conflicts with the application.');
50
+ const rendererIdentity = readRendererIdentity(manifest.rendererIdentity, manifest.rendererIdentity);
51
+ const nativeHydrationBuildId = manifest.nativeHydrationBuildId;
52
+ assertNativeHydrationBuildId(nativeHydrationBuildId);
53
+ if (!Array.isArray(manifest.assets) || !manifest.assets.length) throw new Error('Octane compiler manifest has no emitted JavaScript closure.');
54
+ const assetNames = new Set();
55
+ const assets = manifest.assets.map((value)=>{
56
+ const asset = record(value, [
57
+ 'file',
58
+ 'sha256'
59
+ ]);
60
+ if (!assetPath(asset.file) || !digest(asset.sha256) || assetNames.has(asset.file)) throw new Error('Invalid Octane emitted asset digest.');
61
+ assetNames.add(asset.file);
62
+ return Object.freeze({
63
+ file: asset.file,
64
+ sha256: asset.sha256
65
+ });
66
+ });
67
+ if (!Array.isArray(manifest.sourceModules) || !manifest.sourceModules.length) throw new Error('Octane compiler manifest has no authenticated native sources.');
68
+ const resources = new Set();
69
+ const sourceModules = manifest.sourceModules.map((value)=>{
70
+ const source = record(value, [
71
+ 'resource',
72
+ 'canonicalId',
73
+ 'moduleId',
74
+ 'transformKind',
75
+ 'emittedSourceSha256',
76
+ 'assets'
77
+ ]);
78
+ if (!nonempty(source.resource) || source.resource.startsWith('/') || source.resource.includes('\\') || !nonempty(source.canonicalId) || !('string' == typeof source.moduleId && nonempty(source.moduleId) || 'number' == typeof source.moduleId && Number.isFinite(source.moduleId)) || !('compile' === source.transformKind || 'slots' === source.transformKind || 'client-only-stub' === source.transformKind) || !digest(source.emittedSourceSha256) || !Array.isArray(source.assets) || !source.assets.length || source.assets.some((file)=>'string' != typeof file || !assetNames.has(file)) || new Set(source.assets).size !== source.assets.length || resources.has(source.resource)) throw new Error('Invalid Octane native source-to-asset provenance.');
79
+ resources.add(source.resource);
80
+ return Object.freeze({
81
+ resource: source.resource,
82
+ canonicalId: source.canonicalId,
83
+ moduleId: source.moduleId,
84
+ transformKind: source.transformKind,
85
+ emittedSourceSha256: source.emittedSourceSha256,
86
+ assets: Object.freeze([
87
+ ...source.assets
88
+ ])
89
+ });
90
+ });
91
+ return Object.freeze({
92
+ schemaVersion: 1,
93
+ renderer: 'octane',
94
+ runtimeVersion: OCTANE_RUNTIME_VERSION,
95
+ compilerVersion: OCTANE_COMPILER_VERSION,
96
+ rendererIdentity,
97
+ nativeHydrationBuildId,
98
+ sourceModules: Object.freeze(sourceModules),
99
+ assets: Object.freeze(assets)
100
+ });
101
+ }
102
+ const compilerArtifacts = {
103
+ clientManifestFile: octaneModuleManifestFileName,
104
+ async validateClientManifest (value, identity, context) {
105
+ const hydrationBuildId = context.compilationHash ?? context.hydrationBuildId;
106
+ if (context.development && ('string' != typeof hydrationBuildId || !hydrationBuildId.trim())) throw new Error('Octane development snapshot has no native hydration build.');
107
+ const nativeManifest = validateOctaneModuleManifest(value, identity, hydrationBuildId);
108
+ return {
109
+ nativeManifest,
110
+ hydrationBuildId: nativeManifest.nativeHydrationBuildId
111
+ };
112
+ },
113
+ isMutableDevelopmentAsset (filename, entryNames) {
114
+ return 'octane-client-build.json' === filename || entryNames.some((entry)=>filename === octaneModuleManifestFileName(entry));
115
+ }
116
+ };
117
+ export { OCTANE_COMPILER_VERSION, OCTANE_RUNTIME_VERSION, compilerArtifacts, octaneModuleManifestFileName, validateOctaneModuleManifest };
@@ -0,0 +1,70 @@
1
+ import node_fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import node_path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { OCTANE_COMPILER_VERSION, OCTANE_RUNTIME_VERSION, octaneModuleManifestFileName, validateOctaneModuleManifest } from "../manifest.mjs";
6
+ function pluginSourceDirectory() {
7
+ let directory = node_path.dirname(fileURLToPath(import.meta.url));
8
+ while(true){
9
+ const compiler = node_path.join(directory, 'src/plugin');
10
+ if (node_fs.existsSync(node_path.join(directory, 'package.json')) && node_fs.existsSync(node_path.join(compiler, 'compiler-manifest.cjs'))) return compiler;
11
+ const parent = node_path.dirname(directory);
12
+ if (parent === directory) throw new Error('Cannot locate the UltraModern Octane compiler package.');
13
+ directory = parent;
14
+ }
15
+ }
16
+ function createOctaneCompilerPlugin(options) {
17
+ return {
18
+ name: 'ultramodern:octane:compiler',
19
+ setup (api) {
20
+ const directory = pluginSourceDirectory();
21
+ const require = createRequire(node_path.join(directory, 'index.cjs'));
22
+ const { OctaneCompilerManifestPlugin } = require('./compiler-manifest.cjs');
23
+ const { inferRspackEnvironment, OctaneRspackPlugin } = require('@octanejs/rspack-plugin');
24
+ api.modifyRsbuildConfig((config, { mergeRsbuildConfig })=>mergeRsbuildConfig(config, {
25
+ source: {
26
+ include: [
27
+ /[/\\]@octanejs[/\\]/u
28
+ ]
29
+ }
30
+ }));
31
+ api.modifyRspackConfig((config, { environment: rsbuildEnvironment })=>{
32
+ const environment = rsbuildEnvironment.name === options.workerEnvironmentName ? 'server' : inferRspackEnvironment(config.target);
33
+ config.resolve ??= {};
34
+ const extensions = (config.resolve.extensions ?? []).filter((extension)=>'.tsrx' !== extension);
35
+ extensions.splice(Math.max(extensions.indexOf('.ts'), extensions.indexOf('.tsx')) + 1, 0, '.tsrx');
36
+ config.resolve.extensions = extensions;
37
+ config.plugins ??= [];
38
+ config.plugins.push(new OctaneRspackPlugin({
39
+ root: api.context.rootPath,
40
+ environment,
41
+ transpile: false
42
+ }));
43
+ config.plugins.push(new OctaneCompilerManifestPlugin({
44
+ emitClientManifest: 'client' === environment,
45
+ root: api.context.rootPath,
46
+ runtimeVersion: OCTANE_RUNTIME_VERSION,
47
+ compilerVersion: OCTANE_COMPILER_VERSION,
48
+ rendererIdentities: options.rendererIdentities,
49
+ manifestFilename: octaneModuleManifestFileName,
50
+ validateManifest: validateOctaneModuleManifest
51
+ }));
52
+ config.module ??= {};
53
+ config.module.rules ??= [];
54
+ config.module.rules.push({
55
+ test: /\.tsrx$/u,
56
+ type: "javascript/auto",
57
+ use: [
58
+ {
59
+ loader: 'builtin:swc-loader',
60
+ options: {
61
+ detectSyntax: 'auto'
62
+ }
63
+ }
64
+ ]
65
+ });
66
+ });
67
+ }
68
+ };
69
+ }
70
+ export { createOctaneCompilerPlugin, pluginSourceDirectory };