@inox-tools/request-state 0.1.0 → 0.1.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.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { defineIntegration, addVitePlugin } from 'astro-integration-kit';
1
+ import { defineIntegration, createResolver, addVitePlugin } from 'astro-integration-kit';
2
2
  import { plugin } from './plugin.js';
3
3
 
4
- var u=defineIntegration({name:"@inox-tools/request-state",setup(){return {hooks:{"astro:config:setup":e=>{const{addMiddleware:t}=e;t({order:"pre",entrypoint:"@inox-tools/request-state/runtime/middleware"}),addVitePlugin(e,{warnDuplicated:!0,plugin:plugin()});}}}}});
4
+ var g=defineIntegration({name:"@inox-tools/request-state",setup(){const{resolve:t}=createResolver(import.meta.url);return {hooks:{"astro:config:setup":e=>{const{addMiddleware:r}=e;e.logger.debug("Adding request-state middleware"),r({order:"pre",entrypoint:t("runtime/middleware.js")}),e.logger.debug("Adding request-state virtual module"),addVitePlugin(e,{warnDuplicated:!0,plugin:plugin()});}}}}});
5
5
 
6
- export { u as default };
6
+ export { g as default };
7
7
  //# sourceMappingURL=index.js.map
8
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["src_default","defineIntegration","params","addMiddleware","addVitePlugin","plugin"],"mappings":";;;AAGA,IAAOA,CAAQC,CAAAA,iBAAAA,CAAkB,CAChC,IAAM,CAAA,2BAAA,CACN,KAAQ,EAAA,CACP,OAAO,CACN,MAAO,CACN,oBAAA,CAAuBC,CAAW,EAAA,CACjC,KAAM,CAAE,cAAAC,CAAc,CAAA,CAAID,CAE1BC,CAAAA,CAAAA,CAAc,CACb,KAAA,CAAO,MACP,UAAY,CAAA,8CACb,CAAC,CAAA,CACDC,aAAcF,CAAAA,CAAAA,CAAQ,CACrB,cAAgB,CAAA,CAAA,CAAA,CAChB,MAAQG,CAAAA,MAAAA,EACT,CAAC,EACF,CACD,CACD,CACD,CACD,CAAC","file":"index.js","sourcesContent":["import { defineIntegration, addVitePlugin } from 'astro-integration-kit';\nimport { plugin } from './plugin.js';\n\nexport default defineIntegration({\n\tname: '@inox-tools/request-state',\n\tsetup() {\n\t\treturn {\n\t\t\thooks: {\n\t\t\t\t'astro:config:setup': (params) => {\n\t\t\t\t\tconst { addMiddleware } = params;\n\n\t\t\t\t\taddMiddleware({\n\t\t\t\t\t\torder: 'pre',\n\t\t\t\t\t\tentrypoint: '@inox-tools/request-state/runtime/middleware',\n\t\t\t\t\t});\n\t\t\t\t\taddVitePlugin(params, {\n\t\t\t\t\t\twarnDuplicated: true,\n\t\t\t\t\t\tplugin: plugin(),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t},\n});\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["src_default","defineIntegration","resolve","createResolver","params","addMiddleware","addVitePlugin","plugin"],"mappings":";;;AAGA,IAAOA,CAAQC,CAAAA,iBAAAA,CAAkB,CAChC,IAAM,CAAA,2BAAA,CACN,KAAQ,EAAA,CACP,KAAM,CAAE,OAAA,CAAAC,CAAQ,CAAA,CAAIC,eAAe,MAAY,CAAA,IAAA,CAAA,GAAG,CAElD,CAAA,OAAO,CACN,KAAO,CAAA,CACN,oBAAuBC,CAAAA,CAAAA,EAAW,CACjC,KAAM,CAAE,aAAAC,CAAAA,CAAc,EAAID,CAE1BA,CAAAA,CAAAA,CAAO,MAAO,CAAA,KAAA,CAAM,iCAAiC,CACrDC,CAAAA,CAAAA,CAAc,CACb,KAAA,CAAO,MACP,UAAYH,CAAAA,CAAAA,CAAQ,uBAAuB,CAC5C,CAAC,CAEDE,CAAAA,CAAAA,CAAO,MAAO,CAAA,KAAA,CAAM,qCAAqC,CACzDE,CAAAA,aAAAA,CAAcF,CAAQ,CAAA,CACrB,eAAgB,CAChB,CAAA,CAAA,MAAA,CAAQG,MAAO,EAChB,CAAC,EACF,CACD,CACD,CACD,CACD,CAAC","file":"index.js","sourcesContent":["import { defineIntegration, addVitePlugin, createResolver } from 'astro-integration-kit';\nimport { plugin } from './plugin.js';\n\nexport default defineIntegration({\n\tname: '@inox-tools/request-state',\n\tsetup() {\n\t\tconst { resolve } = createResolver(import.meta.url);\n\n\t\treturn {\n\t\t\thooks: {\n\t\t\t\t'astro:config:setup': (params) => {\n\t\t\t\t\tconst { addMiddleware } = params;\n\n\t\t\t\t\tparams.logger.debug('Adding request-state middleware');\n\t\t\t\t\taddMiddleware({\n\t\t\t\t\t\torder: 'pre',\n\t\t\t\t\t\tentrypoint: resolve('runtime/middleware.js'),\n\t\t\t\t\t});\n\n\t\t\t\t\tparams.logger.debug('Adding request-state virtual module');\n\t\t\t\t\taddVitePlugin(params, {\n\t\t\t\t\t\twarnDuplicated: true,\n\t\t\t\t\t\tplugin: plugin(),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t},\n});\n"]}
package/dist/plugin.js CHANGED
@@ -1,5 +1,10 @@
1
- const e="@it-astro:state",r=`\0${e}`,n=()=>({name:"@inox-tools/request-state/vite-plugin",resolveId(t){if(t===e)return r},load(t,o){return t!==r?void 0:`export {setState, getState} from '@inox-tools/request-state/runtime/${o?.ssr?"serverState":"clientState"}';`}});
1
+ import { createResolver } from 'astro-integration-kit';
2
2
 
3
- export { n as plugin };
3
+ const r="@it-astro:state",s=`\0${r}`,u=()=>{const{resolve:e}=createResolver(import.meta.url);return {name:"@inox-tools/request-state/vite-plugin",resolveId(t){if(t===r)return s},config(t){t.ssr?.external!==!0&&(t.ssr={...t.ssr,external:[...t.ssr?.external??[],"node:async_hooks"]});},load(t,o){if(t!==s)return;const n=o?.ssr?"serverState.js":"clientState.js";return `
4
+ export {setState, getState} from '${e("runtime",n)}';
5
+ export {ServerStateLoaded} from '${e("events.js")}';
6
+ `.trim()}}};
7
+
8
+ export { u as plugin };
4
9
  //# sourceMappingURL=plugin.js.map
5
10
  //# sourceMappingURL=plugin.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/plugin.ts"],"names":["MODULE_ID","RESOLVED_MODULE_ID","plugin","id","options"],"mappings":"AAEA,MAAMA,CAAY,CAAA,iBAAA,CACZC,CAAqB,CAAA,CAAA,EAAA,EAAOD,CAAS,CAE9BE,CAAAA,CAAAA,CAAAA,CAAS,KACd,CACN,KAAM,uCACN,CAAA,SAAA,CAAUC,CAAI,CAAA,CACb,GAAIA,CAAOH,GAAAA,CAAAA,CACV,OAAOC,CAET,CACA,CAAA,IAAA,CAAKE,CAAIC,CAAAA,CAAAA,CAAS,CACjB,OAAID,CAAAA,GAAOF,CAAoB,CAAA,KAAA,CAAA,CAIxB,uEAFaG,CAAS,EAAA,GAAA,CAAM,aAAgB,CAAA,aAEsC,IAC1F,CACD,CAAA","file":"plugin.js","sourcesContent":["import type { Plugin } from 'vite';\n\nconst MODULE_ID = '@it-astro:state';\nconst RESOLVED_MODULE_ID = `\\x00${MODULE_ID}`;\n\nexport const plugin = (): Plugin => {\n\treturn {\n\t\tname: '@inox-tools/request-state/vite-plugin',\n\t\tresolveId(id) {\n\t\t\tif (id === MODULE_ID) {\n\t\t\t\treturn RESOLVED_MODULE_ID;\n\t\t\t}\n\t\t},\n\t\tload(id, options) {\n\t\t\tif (id !== RESOLVED_MODULE_ID) return;\n\n\t\t\tconst stateSource = options?.ssr ? 'serverState' : 'clientState';\n\n\t\t\treturn `export {setState, getState} from '@inox-tools/request-state/runtime/${stateSource}';`;\n\t\t},\n\t};\n};\n"]}
1
+ {"version":3,"sources":["../src/plugin.ts"],"names":["MODULE_ID","RESOLVED_MODULE_ID","plugin","resolve","createResolver","id","config","options","stateSource"],"mappings":";;AAGA,MAAMA,EAAY,iBACZC,CAAAA,CAAAA,CAAqB,CAAOD,EAAAA,EAAAA,CAAS,GAE9BE,CAAS,CAAA,IAAc,CACnC,KAAM,CAAE,OAAAC,CAAAA,CAAQ,CAAIC,CAAAA,cAAAA,CAAe,YAAY,GAAG,CAAA,CAElD,OAAO,CACN,KAAM,uCACN,CAAA,SAAA,CAAUC,CAAI,CAAA,CACb,GAAIA,CAAOL,GAAAA,CAAAA,CACV,OAAOC,CAET,EACA,MAAOK,CAAAA,CAAAA,CAAQ,CACVA,CAAAA,CAAO,GAAK,EAAA,QAAA,GAAa,CAE7BA,CAAAA,GAAAA,CAAAA,CAAO,IAAM,CACZ,GAAGA,CAAO,CAAA,GAAA,CACV,SAAU,CAAC,GAAIA,CAAO,CAAA,GAAA,EAAK,UAAY,EAAC,CAAI,kBAAkB,CAC/D,GACD,CACA,CAAA,IAAA,CAAKD,CAAIE,CAAAA,CAAAA,CAAS,CACjB,GAAIF,CAAAA,GAAOJ,CAAoB,CAAA,OAE/B,MAAMO,CAAcD,CAAAA,CAAAA,EAAS,GAAM,CAAA,gBAAA,CAAmB,iBAGtD,OAAO,CAAA;AAAA,kCAFYJ,EAAAA,CAAAA,CAAQ,SAAWK,CAAAA,CAAW,CAGN,CAAA;AAAA,iCACXL,EAAAA,CAAAA,CAAQ,WAAW,CAAC,CAAA;AAAA,CACrD,CAAA,IAAA,EACA,CACD,CACD","file":"plugin.js","sourcesContent":["import { createResolver } from 'astro-integration-kit';\nimport type { Plugin } from 'vite';\n\nconst MODULE_ID = '@it-astro:state';\nconst RESOLVED_MODULE_ID = `\\x00${MODULE_ID}`;\n\nexport const plugin = (): Plugin => {\n\tconst { resolve } = createResolver(import.meta.url);\n\n\treturn {\n\t\tname: '@inox-tools/request-state/vite-plugin',\n\t\tresolveId(id) {\n\t\t\tif (id === MODULE_ID) {\n\t\t\t\treturn RESOLVED_MODULE_ID;\n\t\t\t}\n\t\t},\n\t\tconfig(config) {\n\t\t\tif (config.ssr?.external === true) return;\n\n\t\t\tconfig.ssr = {\n\t\t\t\t...config.ssr,\n\t\t\t\texternal: [...(config.ssr?.external ?? []), 'node:async_hooks'],\n\t\t\t};\n\t\t},\n\t\tload(id, options) {\n\t\t\tif (id !== RESOLVED_MODULE_ID) return;\n\n\t\t\tconst stateSource = options?.ssr ? 'serverState.js' : 'clientState.js';\n\t\t\tconst importPath = resolve('runtime', stateSource);\n\n\t\t\treturn `\nexport {setState, getState} from '${importPath}';\nexport {ServerStateLoaded} from '${resolve('events.js')}';\n`.trim();\n\t\t},\n\t};\n};\n"]}
@@ -2,7 +2,7 @@ import { defineMiddleware } from 'astro/middleware';
2
2
  import { collectState } from './serverState.js';
3
3
  import { parse } from 'content-type';
4
4
 
5
- const u=defineMiddleware(async(l,o)=>{const{getState:n,result:t}=await collectState(o),e=t.headers.get("Content-Type");if(e===null)return t;const{type:r}=parse(e);if(r!=="text/html"&&!r.startsWith("text/html+"))return t;async function*s(){for await(const i of t.body)yield i;const a=n();a&&(yield `<script id="it-astro-state" type="application/json+devalue">${a}</script>`);}return new Response(s(),t)});
5
+ const u=defineMiddleware(async(i,n)=>{const{getState:e,result:t}=await collectState(n),r=t.headers.get("Content-Type");if(r===null)return t;const{type:o}=parse(r);if(o!=="text/html"&&!o.startsWith("text/html+"))return t;const s=t.body?.pipeThrough(new TextDecoderStream).pipeThrough(d(e)).pipeThrough(new TextEncoderStream);return new Response(s,t)});function d(i){let n=!1;return new TransformStream({transform(e,t){if(!n){const r=e.indexOf("</body>");if(r>-1){const o=i();if(o){const s=`<script id="it-astro-state" type="application/json+devalue">${o}</script>`;e=e.slice(0,r)+s+e.slice(r);}n=!0;}}t.enqueue(e);}})}
6
6
 
7
7
  export { u as onRequest };
8
8
  //# sourceMappingURL=middleware.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/runtime/middleware.ts"],"names":["onRequest","defineMiddleware","_","next","getState","result","collectState","contentType","mediaType","parse","render","chunk","state"],"mappings":";;;;MAKaA,CAAYC,CAAAA,gBAAAA,CAAiB,MAAOC,CAAGC,CAAAA,CAAAA,GAAS,CAC5D,KAAM,CAAE,QAAAC,CAAAA,CAAAA,CAAU,OAAAC,CAAO,CAAA,CAAI,MAAMC,YAAaH,CAAAA,CAAI,EAE9CI,CAAcF,CAAAA,CAAAA,CAAO,OAAQ,CAAA,GAAA,CAAI,cAAc,CAErD,CAAA,GAAIE,IAAgB,IAAM,CAAA,OAAOF,EAEjC,KAAM,CAAE,IAAMG,CAAAA,CAAU,EAAIC,KAAMF,CAAAA,CAAW,EAE7C,GAAIC,CAAAA,GAAc,aAAe,CAACA,CAAAA,CAAU,UAAW,CAAA,YAAY,EAAG,OAAOH,CAAAA,CAE7E,eAAgBK,CAAS,EAAA,CACxB,gBAAiBC,CAASN,IAAAA,CAAAA,CAAO,IAChC,CAAA,MAAMM,EAGP,MAAMC,CAAAA,CAAQR,GAEVQ,CAAAA,CAAAA,GACH,MAAM,CAA+DA,4DAAAA,EAAAA,CAAK,CAE5E,SAAA,CAAA,EAAA,CAGA,OAAO,IAAI,QAAA,CAASF,GAAUL,CAAAA,CAAM,CACrC,CAAC","file":"middleware.js","sourcesContent":["import type { ReadableStream } from 'node:stream/web';\nimport { defineMiddleware } from 'astro/middleware';\nimport { collectState } from './serverState.js';\nimport { parse } from 'content-type';\n\nexport const onRequest = defineMiddleware(async (_, next) => {\n\tconst { getState, result } = await collectState(next);\n\n\tconst contentType = result.headers.get('Content-Type');\n\n\tif (contentType === null) return result;\n\n\tconst { type: mediaType } = parse(contentType);\n\n\tif (mediaType !== 'text/html' && !mediaType.startsWith('text/html+')) return result;\n\n\tasync function* render() {\n\t\tfor await (const chunk of result.body as ReadableStream<ArrayBuffer>) {\n\t\t\tyield chunk;\n\t\t}\n\n\t\tconst state = getState();\n\n\t\tif (state) {\n\t\t\tyield `<script id=\"it-astro-state\" type=\"application/json+devalue\">${state}</script>`;\n\t\t}\n\t}\n\n\t// @ts-expect-error generator not assignable to ReadableStream\n\treturn new Response(render(), result);\n});\n"]}
1
+ {"version":3,"sources":["../../src/runtime/middleware.ts"],"names":["onRequest","defineMiddleware","_","next","getState","result","collectState","contentType","mediaType","parse","newBody","injectState","injected","chunk","controller","bodyCloseIndex","state","stateScript"],"mappings":";;;;AAIaA,MAAAA,CAAAA,CAAYC,iBAAiB,MAAOC,CAAAA,CAAGC,CAAS,GAAA,CAC5D,KAAM,CAAE,QAAAC,CAAAA,CAAAA,CAAU,OAAAC,CAAO,CAAA,CAAI,MAAMC,YAAAA,CAAaH,CAAI,CAE9CI,CAAAA,CAAAA,CAAcF,CAAO,CAAA,OAAA,CAAQ,IAAI,cAAc,CAAA,CAErD,GAAIE,CAAAA,GAAgB,IAAM,CAAA,OAAOF,CAEjC,CAAA,KAAM,CAAE,IAAMG,CAAAA,CAAU,CAAIC,CAAAA,KAAAA,CAAMF,CAAW,CAE7C,CAAA,GAAIC,CAAc,GAAA,WAAA,EAAe,CAACA,CAAU,CAAA,UAAA,CAAW,YAAY,CAAA,CAAG,OAAOH,CAAAA,CAE7E,MAAMK,CAAAA,CAAUL,EAAO,IACpB,EAAA,WAAA,CAAY,IAAI,iBAAmB,EACpC,WAAYM,CAAAA,CAAAA,CAAYP,CAAQ,CAAC,EACjC,WAAY,CAAA,IAAI,iBAAmB,CAAA,CAErC,OAAO,IAAI,QAASM,CAAAA,CAAAA,CAASL,CAAM,CACpC,CAAC,EAED,SAASM,CAAYP,CAAAA,CAAAA,CAAgC,CACpD,IAAIQ,EAAW,CACf,CAAA,CAAA,OAAO,IAAI,eAAA,CAAgB,CAC1B,SAAA,CAAUC,CAAOC,CAAAA,CAAAA,CAAY,CAC5B,GAAI,CAACF,CAAU,CAAA,CACd,MAAMG,CAAiBF,CAAAA,CAAAA,CAAM,OAAQ,CAAA,SAAS,EAC9C,GAAIE,CAAAA,CAAiB,CAAI,CAAA,CAAA,CACxB,MAAMC,CAAAA,CAAQZ,CAAS,EAAA,CACvB,GAAIY,CAAO,CAAA,CACV,MAAMC,CAAAA,CAAc,+DAA+DD,CAAK,CAAA,SAAA,CAAA,CAExFH,CAAQA,CAAAA,CAAAA,CAAM,MAAM,CAAGE,CAAAA,CAAc,CAAIE,CAAAA,CAAAA,CAAcJ,CAAM,CAAA,KAAA,CAAME,CAAc,EAClF,CACAH,CAAW,CAAA,CAAA,EACZ,CACD,CACAE,EAAW,OAAQD,CAAAA,CAAK,EACzB,CACD,CAAC,CACF","file":"middleware.js","sourcesContent":["import { defineMiddleware } from 'astro/middleware';\nimport { collectState } from './serverState.js';\nimport { parse } from 'content-type';\n\nexport const onRequest = defineMiddleware(async (_, next) => {\n\tconst { getState, result } = await collectState(next);\n\n\tconst contentType = result.headers.get('Content-Type');\n\n\tif (contentType === null) return result;\n\n\tconst { type: mediaType } = parse(contentType);\n\n\tif (mediaType !== 'text/html' && !mediaType.startsWith('text/html+')) return result;\n\n\tconst newBody = result.body\n\t\t?.pipeThrough(new TextDecoderStream())\n\t\t.pipeThrough(injectState(getState))\n\t\t.pipeThrough(new TextEncoderStream());\n\n\treturn new Response(newBody, result);\n});\n\nfunction injectState(getState: () => string | false) {\n\tlet injected = false;\n\treturn new TransformStream({\n\t\ttransform(chunk, controller) {\n\t\t\tif (!injected) {\n\t\t\t\tconst bodyCloseIndex = chunk.indexOf('</body>');\n\t\t\t\tif (bodyCloseIndex > -1) {\n\t\t\t\t\tconst state = getState();\n\t\t\t\t\tif (state) {\n\t\t\t\t\t\tconst stateScript = `<script id=\"it-astro-state\" type=\"application/json+devalue\">${state}</script>`;\n\n\t\t\t\t\t\tchunk = chunk.slice(0, bodyCloseIndex) + stateScript + chunk.slice(bodyCloseIndex);\n\t\t\t\t\t}\n\t\t\t\t\tinjected = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk);\n\t\t},\n\t});\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inox-tools/request-state",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Shared request state between server and client",
5
5
  "keywords": [
6
6
  "astro-integration",
@@ -14,14 +14,6 @@
14
14
  ".": {
15
15
  "types": "./dist/index.d.ts",
16
16
  "default": "./dist/index.js"
17
- },
18
- "./events": {
19
- "types": "./dist/events.d.ts",
20
- "default": "./dist/events.js"
21
- },
22
- "./runtime/*": {
23
- "types": "./dist/runtime/*.d.ts",
24
- "default": "./dist/runtime/*.js"
25
17
  }
26
18
  },
27
19
  "files": [
package/src/index.ts CHANGED
@@ -1,18 +1,23 @@
1
- import { defineIntegration, addVitePlugin } from 'astro-integration-kit';
1
+ import { defineIntegration, addVitePlugin, createResolver } from 'astro-integration-kit';
2
2
  import { plugin } from './plugin.js';
3
3
 
4
4
  export default defineIntegration({
5
5
  name: '@inox-tools/request-state',
6
6
  setup() {
7
+ const { resolve } = createResolver(import.meta.url);
8
+
7
9
  return {
8
10
  hooks: {
9
11
  'astro:config:setup': (params) => {
10
12
  const { addMiddleware } = params;
11
13
 
14
+ params.logger.debug('Adding request-state middleware');
12
15
  addMiddleware({
13
16
  order: 'pre',
14
- entrypoint: '@inox-tools/request-state/runtime/middleware',
17
+ entrypoint: resolve('runtime/middleware.js'),
15
18
  });
19
+
20
+ params.logger.debug('Adding request-state virtual module');
16
21
  addVitePlugin(params, {
17
22
  warnDuplicated: true,
18
23
  plugin: plugin(),
package/src/plugin.ts CHANGED
@@ -1,9 +1,12 @@
1
+ import { createResolver } from 'astro-integration-kit';
1
2
  import type { Plugin } from 'vite';
2
3
 
3
4
  const MODULE_ID = '@it-astro:state';
4
5
  const RESOLVED_MODULE_ID = `\x00${MODULE_ID}`;
5
6
 
6
7
  export const plugin = (): Plugin => {
8
+ const { resolve } = createResolver(import.meta.url);
9
+
7
10
  return {
8
11
  name: '@inox-tools/request-state/vite-plugin',
9
12
  resolveId(id) {
@@ -11,12 +14,24 @@ export const plugin = (): Plugin => {
11
14
  return RESOLVED_MODULE_ID;
12
15
  }
13
16
  },
17
+ config(config) {
18
+ if (config.ssr?.external === true) return;
19
+
20
+ config.ssr = {
21
+ ...config.ssr,
22
+ external: [...(config.ssr?.external ?? []), 'node:async_hooks'],
23
+ };
24
+ },
14
25
  load(id, options) {
15
26
  if (id !== RESOLVED_MODULE_ID) return;
16
27
 
17
- const stateSource = options?.ssr ? 'serverState' : 'clientState';
28
+ const stateSource = options?.ssr ? 'serverState.js' : 'clientState.js';
29
+ const importPath = resolve('runtime', stateSource);
18
30
 
19
- return `export {setState, getState} from '@inox-tools/request-state/runtime/${stateSource}';`;
31
+ return `
32
+ export {setState, getState} from '${importPath}';
33
+ export {ServerStateLoaded} from '${resolve('events.js')}';
34
+ `.trim();
20
35
  },
21
36
  };
22
37
  };
@@ -1,4 +1,3 @@
1
- import type { ReadableStream } from 'node:stream/web';
2
1
  import { defineMiddleware } from 'astro/middleware';
3
2
  import { collectState } from './serverState.js';
4
3
  import { parse } from 'content-type';
@@ -14,18 +13,31 @@ export const onRequest = defineMiddleware(async (_, next) => {
14
13
 
15
14
  if (mediaType !== 'text/html' && !mediaType.startsWith('text/html+')) return result;
16
15
 
17
- async function* render() {
18
- for await (const chunk of result.body as ReadableStream<ArrayBuffer>) {
19
- yield chunk;
20
- }
16
+ const newBody = result.body
17
+ ?.pipeThrough(new TextDecoderStream())
18
+ .pipeThrough(injectState(getState))
19
+ .pipeThrough(new TextEncoderStream());
21
20
 
22
- const state = getState();
23
-
24
- if (state) {
25
- yield `<script id="it-astro-state" type="application/json+devalue">${state}</script>`;
26
- }
27
- }
28
-
29
- // @ts-expect-error generator not assignable to ReadableStream
30
- return new Response(render(), result);
21
+ return new Response(newBody, result);
31
22
  });
23
+
24
+ function injectState(getState: () => string | false) {
25
+ let injected = false;
26
+ return new TransformStream({
27
+ transform(chunk, controller) {
28
+ if (!injected) {
29
+ const bodyCloseIndex = chunk.indexOf('</body>');
30
+ if (bodyCloseIndex > -1) {
31
+ const state = getState();
32
+ if (state) {
33
+ const stateScript = `<script id="it-astro-state" type="application/json+devalue">${state}</script>`;
34
+
35
+ chunk = chunk.slice(0, bodyCloseIndex) + stateScript + chunk.slice(bodyCloseIndex);
36
+ }
37
+ injected = true;
38
+ }
39
+ }
40
+ controller.enqueue(chunk);
41
+ },
42
+ });
43
+ }
package/virtual.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  declare module '@it-astro:state' {
2
2
  export const getState: (key: string, valueIfMissing?: unknown) => unknown;
3
3
  export const setState: (key: string, value: unknown) => void;
4
+
5
+ export { ServerStateLoaded } from './src/events.js';
4
6
  }
5
7
 
6
8
  declare global {
7
9
  interface DocumentEventMap {
8
- [ServerStateLoaded.NAME]: import('@inox-tools/request-state/events').ServerStateLoaded;
10
+ [ServerStateLoaded.NAME]: import('./src/events.js').ServerStateLoaded;
9
11
  }
10
12
  }
package/dist/events.d.ts DELETED
@@ -1,33 +0,0 @@
1
- /// <reference path="../virtual.d.ts" />
2
-
3
- type State = Map<string, unknown>;
4
- declare class ServerStateLoaded extends Event {
5
- /**
6
- * The client state before loading the server state.
7
- *
8
- * On first load, this will be an empty map.
9
- * When using View Transitions and navigating to another page,
10
- * this will be state of the previous page.
11
- */
12
- readonly previousState: State;
13
- /**
14
- * The server state that will be loaded.
15
- */
16
- readonly serverState: State;
17
- static NAME: "@it-astro:server-state-loaded";
18
- constructor(
19
- /**
20
- * The client state before loading the server state.
21
- *
22
- * On first load, this will be an empty map.
23
- * When using View Transitions and navigating to another page,
24
- * this will be state of the previous page.
25
- */
26
- previousState: State,
27
- /**
28
- * The server state that will be loaded.
29
- */
30
- serverState: State, options?: EventInit);
31
- }
32
-
33
- export { ServerStateLoaded, type State };