@teacss/runtime 0.3.0

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2021-PRESENT Anthony Fu <https://github.com/antfu>
4
+ Copyright (c) 2026-PRESENT Billgo <hi@billgo.me>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # @teacss/runtime
2
+
3
+ **Shared runtime for TeaCSS build integrations.**
4
+
5
+ ## Purpose
6
+
7
+ This package creates generator contexts, loads CSS-entry configuration, tracks
8
+ source modules, and runs source transformers. It keeps build-pipeline concerns
9
+ out of `@teacss/core` and preset packages.
10
+
11
+ CLI, build-tool, and editor integrations use it as the shared stateful
12
+ orchestration layer around `@teacss/config` and `@teacss/core`. It does not
13
+ define utility vocabulary or provide application-facing class composition, and
14
+ applications should normally use a concrete TeaCSS integration instead.
15
+
16
+ Use `applyTransformerPipeline` for the standard `pre` → `default` → `post`
17
+ sequence; `applyTransformers` remains available when an integration needs one
18
+ phase explicitly. Stateful transformers can implement `onModuleRemoved(id, ctx)`
19
+ to release module-owned registrations when a build integration deletes a source
20
+ module.
21
+
22
+ Configuration reloads are transactional. The runtime resolves a candidate
23
+ configuration, replays tracked sources through its transformers and extractors,
24
+ and settles staged tasks before switching the live configuration, modules, and
25
+ tokens together. A failed candidate leaves the last successful runtime state
26
+ active. The configuration source list still follows the latest resolved attempt
27
+ so build integrations can watch candidate dependencies and recover from a later
28
+ file change, including when the initial attempt rejects because a dependency is
29
+ missing. For an explicit CSS entry, `content.pipeline` globs resolve from the
30
+ entry's directory. Module ids are matched after their complete query or hash
31
+ suffix is removed. Once the new snapshot commits, lifecycle observers and
32
+ cleanup hooks are isolated and reported as diagnostics rather than turning the
33
+ successful reload into a rollback-style rejection. `ctx.modules` contains only
34
+ currently included modules; the runtime
35
+ can retain an original source or last extracted content internally so a later
36
+ filter expansion can reactivate them without replaying transformed content as
37
+ source.
38
+ The read-only `getModuleOutput(ctx, id)` helper is a build-integration API.
39
+ Unlike active-only `ctx.modules`, it can expose the latest successful
40
+ full-pipeline output from an `idFilter` transformer even when global content
41
+ filtering excludes that module. Failed transforms and failed configuration
42
+ replays retain the last successful output; deleting the module clears it.
43
+
44
+ Transforms for the same module may overlap. Full pipelines, and explicit calls
45
+ within the same phase, reconcile to the latest source and transformer context,
46
+ so a superseded call resolves with the latest transformed output instead of
47
+ publishing stale state. Stateful transformers should therefore key state by the
48
+ passed `ctx` (or its `ctx.generator`) rather than a global module-ID-only store:
49
+ staging and completed configuration generations use isolated contexts.
50
+ `onModuleRemoved` must be idempotent because deletion, reload, and late transform
51
+ reconciliation can call cleanup more than once before replaying the current
52
+ source.
53
+
54
+ `onReload` and `onInvalidate` subscriptions return a disposer. Integrations that
55
+ own shorter-lived contexts should call it when that context is released.
56
+
57
+ It is used by the CLI, Vite, PostCSS, language-service, and related tooling.
58
+
59
+ ## Source generation
60
+
61
+ Node-based integrations can use the public source-generation subpath to share
62
+ TeaCSS's file reading, extraction, and token aggregation behavior:
63
+
64
+ ```ts
65
+ import {
66
+ DEFAULT_SOURCE_IGNORE,
67
+ generateSources,
68
+ readSourceFile,
69
+ } from "@teacss/runtime/source-generation";
70
+ ```
71
+
72
+ `readSourceFile` treats a missing file as empty content, while other file-system
73
+ errors are preserved. `generateSources` applies configured extractors when file
74
+ paths are present and otherwise generates directly from the provided source
75
+ content.
76
+
77
+ ## Status
78
+
79
+ Pre-1.0 public API for build integration authors. Prefer a TeaCSS integration
80
+ unless you are extending the pipeline.
@@ -0,0 +1,31 @@
1
+ import { LoadConfigResult } from "@teacss/config";
2
+ import { SourceCodeTransformerEnforce, TeacssPluginContext, UserConfig, UserConfigDefaults } from "@teacss/core";
3
+ import { EncodedSourceMap } from "@jridgewell/remapping";
4
+ //#region src/context.d.ts
5
+ declare function createContext<Config extends UserConfig<any> = UserConfig<any>>(configOrPath?: Config | string, defaults?: UserConfigDefaults, resolveConfigResult?: (config: LoadConfigResult<Config>) => void): TeacssPluginContext<Config>;
6
+ //#endregion
7
+ //#region src/defaults.d.ts
8
+ declare const defaultPipelineExclude: RegExp[];
9
+ declare const defaultPipelineInclude: RegExp[];
10
+ declare const defaultFilesystemGlobs: string[];
11
+ //#endregion
12
+ //#region src/module-state.d.ts
13
+ /**
14
+ * Read the last successful full-pipeline output tracked for a module.
15
+ *
16
+ * Build-integration API. Use `ctx.modules` for active extracted modules.
17
+ */
18
+ declare function getModuleOutput(context: TeacssPluginContext, id: string): string | undefined;
19
+ //#endregion
20
+ //#region src/transformers.d.ts
21
+ declare function applyTransformers(ctx: TeacssPluginContext, original: string, id: string, enforce?: SourceCodeTransformerEnforce): Promise<{
22
+ code: string;
23
+ map: EncodedSourceMap;
24
+ } | undefined>;
25
+ /** Run source transformers in their stable pre → default → post order. */
26
+ declare function applyTransformerPipeline(ctx: TeacssPluginContext, original: string, id: string): Promise<{
27
+ code: string;
28
+ map: EncodedSourceMap;
29
+ } | undefined>;
30
+ //#endregion
31
+ export { applyTransformerPipeline, applyTransformers, createContext, defaultFilesystemGlobs, defaultPipelineExclude, defaultPipelineInclude, getModuleOutput };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{dirname as e,resolve as t}from"node:path";import n from"node:process";import{createRecoveryConfigLoader as r,getConfigSourcesFromError as i}from"@teacss/config";import{BetterMap as a,CSS_PLACEHOLDER as o,IGNORE_COMMENT as s,INCLUDE_COMMENT as c,SKIP_END_COMMENT as l,SKIP_START_COMMENT as u,createGenerator as d,escapeRegExp as f,extractorSplit as p,hash as m}from"@teacss/core";import{createFilter as h}from"unplugin-utils";import{AsyncLocalStorage as g}from"node:async_hooks";import _ from"magic-string";import v from"@jridgewell/remapping";const y=[/\.(css|postcss|sass|scss|less|stylus|styl)($|\?)/],b=[/\.(vue|svelte|[jt]sx|vine.ts|mdx?|astro|elm|php|phtml|marko|html)($|\?)/],x=[`**/*.{html,js,ts,jsx,tsx,vue,svelte,astro,elm,php,phtml,mdx,md,marko}`];function ee(e){return{envMode:e.envMode,extractors:e.extractors.map(e=>[e,e.extract])}}function S(e,t){return e!==void 0&&e.envMode===t.envMode&&e.extractors.length===t.extractors.length&&e.extractors.every(([e,n],r)=>e===t.extractors[r]&&n===e.extract)}const C=new WeakMap,w=new g;function T(e,t){let n=w.getStore();return n?.active===!0&&n.context===e&&n.activeIds.has(t)}function E(e,t){let n=w.getStore();n?.active===!0&&n.context===e&&n.stagedLifecycleIds?.has(t)&&(n.stagedLifecycleMutations?.add(t),n.onStagedLifecycleMutation?.(t))}function D(e,t){let n=w.getStore();return n?.active===!0&&n.context===e&&(n.activeIds.has(t)||n.stagedLifecycleIds?.has(t)===!0)}async function te(e,t,n,r,i,a){let o=w.getStore(),s=o?.active===!0&&o.context===e?o:void 0,c=new Set(s?.activeIds);c.add(t);let l={active:!0,activeIds:c,context:e,onStagedLifecycleMutation:a??s?.onStagedLifecycleMutation,stagedLifecycleIds:r??s?.stagedLifecycleIds,stagedLifecycleMutations:i??s?.stagedLifecycleMutations};return await w.run(l,async()=>{try{return await n()}finally{l.active=!1}})}function O(e){let t=C.get(e);return t||(t={contents:new Map,inFlightTransforms:new Map,locks:new Map,outputs:new Map,phaseRequests:new Map,phaseSuccessfulSources:new Map,pipelineRequestCounts:new Map,pipelineSources:new Map,pipelineVersions:new Map,removalVersions:new Map,sources:new Map,successfulSources:new Map,transformBarriers:new Map},C.set(e,t)),t}function k(e,t,n,r){let i=O(e),a=i.phaseRequests.get(t);a||(a=new Map,i.phaseRequests.set(t,a));let o=a.get(n),s={count:(o?.count??0)+1,source:r,version:(o?.version??0)+1};return a.set(n,s),{removalVersion:i.removalVersions.get(t)??0,version:s.version}}function A(e,t,n){let r=O(e),i=r.phaseRequests.get(t),a=i?.get(n);!i||!a||(a.count>1?a.count--:i.delete(n),i.size||r.phaseRequests.delete(t),B(r,t))}function j(e,t,n){return O(e).phaseRequests.get(t)?.get(n)?.source}function M(e,t,n){return O(e).phaseRequests.get(t)?.get(n)?.version??0}function N(e,t,n,r){let i=O(e),a=i.phaseSuccessfulSources.get(t);a||(a=new Map,i.phaseSuccessfulSources.set(t,a)),a.set(n,r)}function P(e,t,n){return O(e).phaseSuccessfulSources.get(t)?.get(n)}function ne(e,t,n){let r=O(e),i=(r.pipelineVersions.get(t)??0)+1;return r.pipelineRequestCounts.set(t,(r.pipelineRequestCounts.get(t)??0)+1),r.pipelineSources.set(t,n),r.pipelineVersions.set(t,i),{removalVersion:r.removalVersions.get(t)??0,version:i}}function re(e,t){let n=O(e),r=(n.pipelineRequestCounts.get(t)??1)-1;r>0?n.pipelineRequestCounts.set(t,r):n.pipelineRequestCounts.delete(t),B(n,t)}function F(e,t){return O(e).pipelineVersions.get(t)??0}function ie(e,t){return O(e).pipelineSources.get(t)}function I(e,t){return O(e).removalVersions.get(t)??0}async function ae(e,t,n){let r=O(e);if(!D(e,t))for(;;){let e=r.locks.get(t);if(e){await e;continue}if(n){let e=r.transformBarriers.get(t);if(e){await e;continue}}break}let i=()=>{},a=new Promise(e=>{i=e}),o=r.inFlightTransforms.get(t);o||(o=new Set,r.inFlightTransforms.set(t,o)),o.add(a);let s=r.removalVersions.get(t)??0,c=!1;return{removalVersion:s,finish(){c||(c=!0,o.delete(a),o.size||r.inFlightTransforms.delete(t),B(r,t),i())}}}async function L(e,t){return await ae(e,t,!0)}async function oe(e,t){return await ae(e,t,!1)}function se(e,t){let n=O(e);n.removalVersions.set(t,(n.removalVersions.get(t)??0)+1);let r=Array.from(n.inFlightTransforms.get(t)??[]);if(!r.length){B(n,t);return}let i=Promise.allSettled(r).then(()=>{n.transformBarriers.get(t)===i&&n.transformBarriers.delete(t)});n.transformBarriers.set(t,i)}function R(e,t,n){return(O(e).removalVersions.get(t)??0)!==n}function ce(e,t,n){E(e,t);let r=O(e);r.pipelineSources.set(t,n),r.sources.set(t,n)}function le(e,t,n){O(e).contents.set(t,n)}function ue(e,t){O(e).contents.delete(t)}function de(e,t){return O(e).contents.get(t)}function fe(e){return O(e).contents.entries()}function pe(e,t){let n=O(e);n.pipelineSources.delete(t),n.sources.delete(t),B(n,t)}function me(e,t){return O(e).sources.get(t)}function he(e){return O(e).sources.entries()}function ge(e,t,n,r){E(e,t);let i=O(e);i.outputs.set(t,n),i.phaseSuccessfulSources.delete(t),i.successfulSources.set(t,r)}function _e(e,t){return O(e).successfulSources.get(t)}function ve(e,t){let n=O(e);n.outputs.delete(t),n.phaseSuccessfulSources.delete(t),n.successfulSources.delete(t)}function z(e,t){return O(e).outputs.get(t)}async function ye(e,t){if(D(e,t))return()=>{};let n=O(e),r=n.locks.get(t),i=()=>{},a=new Promise(e=>{i=e});n.locks.set(t,a),await r;let o=!1;return()=>{o||(o=!0,n.locks.get(t)===a&&n.locks.delete(t),i())}}function B(e,t){e.inFlightTransforms.has(t)||e.outputs.has(t)||e.phaseRequests.has(t)||e.phaseSuccessfulSources.has(t)||e.pipelineRequestCounts.has(t)||e.pipelineSources.has(t)||e.sources.has(t)||e.successfulSources.has(t)||(e.pipelineVersions.delete(t),e.removalVersions.delete(t))}async function be(e,t,n,r,i,a,o){let s=[];for(let c of e)try{if(!(`onModuleRemoved`in c))continue;await te(r,t,async()=>{await c.onModuleRemoved?.(t,n)},i,a,o)}catch(e){s.push(e)}return s}const xe=RegExp(`(//\\s*?${u}\\s*?|\\/\\*\\s*?${u}\\s*?\\*\\/|<!--\\s*?${u}\\s*?-->)[\\s\\S]*?(//\\s*?${l}\\s*?|\\/\\*\\s*?${l}\\s*?\\*\\/|<!--\\s*?${l}\\s*?-->)`,`g`),V=/\/\*~[\da-z]{6}/g,Se=/[\da-z]{6}~\*\//g;function Ce(e){return e.includes(u)&&e.includes(l)}function we(e,t){if(!Ce(e))return e;let n=new Set(e.match(V)??[]),r=new Set(e.match(Se)??[]),i=new Set([...t.keys(),...n]),a=new Map;return e.replace(xe,e=>{let o=a.get(e);if(o)return J(e,o);let s=m(e),c=0,l;for(;l=`/*~${c?m(`${s}:${c}`):s}`,c++,!(t.get(l)===e&&!n.has(l)&&!r.has(Ge(l))||!i.has(l)&&!r.has(Ge(l))););return i.add(l),t.set(l,e),a.set(e,l),J(e,l)})}function Te(e,t){let n=Ke(e,t);if(!n.valid)return{anchorsValid:!1,code:e,restoredCount:0,restoredPlaceholders:new Map};let r=new _(e),i=n.regions;for(let t of i){let n=J(t.skipped,t.placeholder),i=e.slice(t.start,t.end);i!==n&&(Je(i,t.start,n,r)||r.overwrite(t.start,t.end,n))}let a=r.toString(),o=new _(a);for(let e of a.matchAll(V)){let n=t.get(e[0]);if(n===void 0)continue;let r=J(n,e[0]);a.startsWith(r,e.index)&&o.overwrite(e.index,e.index+r.length,n)}let s=new Map;for(let{placeholder:e}of i)s.set(e,(s.get(e)??0)+1);return{anchorsValid:!0,code:o.toString(),normalizer:r.hasChanged()?r:void 0,restoredCount:i.length,restoredPlaceholders:s}}const H=new WeakMap;var Ee=class extends _{appendLeft(...e){return super.appendLeft(...e),e[1]&&G(this,`appendLeft`,e),this}appendRight(...e){return super.appendRight(...e),e[1]&&G(this,`appendRight`,e),this}move(...e){return super.move(...e),e[0]===e[1]||Ie(this,{end:K(this,e[1]),index:K(this,e[2]),kind:`move`,start:K(this,e[0])}),this}prependLeft(...e){return super.prependLeft(...e),e[1]&&G(this,`prependLeft`,e),this}prependRight(...e){return super.prependRight(...e),e[1]&&G(this,`prependRight`,e),this}remove(...e){return super.remove(...e),e[0]!==e[1]&&Le(this,`remove`,e[0],e[1],!0),this}reset(...e){return super.reset(...e),e[0]!==e[1]&&Le(this,`reset`,e[0],e[1],!0),this}update(...e){return super.update(...e),Le(this,`update`,e[0],e[1],typeof e[3]==`object`&&e[3].overwrite===!0),this}};function U(e,t){let n=Ke(e,t);if(!n.valid)throw Error(`Failed to prepare skipped source`);let r=n.regions.filter(({end:t,placeholder:n,skipped:r,start:i})=>e.slice(i,t)===J(r,n)).map(({end:e,placeholder:t,start:n})=>({end:e,placeholder:t,start:n})),i={indentExclusionRanges:r.map(({end:e,start:t})=>[t,e])},a=r.length?new Ee(e,i):new _(e,i);r.length&&H.set(a,[]);for(let{end:e,start:t}of r)a.appendLeft(t,``),a.appendLeft(e,``);return{regions:r,s:a}}function De(e,t,n){for(let{end:n,start:r}of t)e.reset(r,n);Re(e,n,t)}function Oe(e,t){let n=new Set;for(let[r,i]of Me(e,t))i.exact&&n.add(r);return n}function ke(e,t,n){let r=new Map;for(let{placeholder:e}of n)r.set(e,(r.get(e)??0)+1);for(let[t,n]of e.restoredPlaceholders)r.set(t,Math.max(0,(r.get(t)??0)-n));let i=[];for(let e of t){let t=r.get(e.placeholder)??0;t&&(i.push(e),r.set(e.placeholder,t-1))}return i}function Ae(e,t){let n=!1;for(let r of H.get(e)??[]){if(r.kind===`move`){if(He(r,t))return!1;continue}let e=r.kind===`insert`?Ve(t,r.index):Be(t,r.start,r.end);if(e&&(n=!0,r.kind!==`insert`&&(r.start<e.start||r.end>e.end)))return!1}return n}function W(e,t){return(H.get(e)??[]).some(e=>e.kind===`move`&&He(e,t))}function je(e,t,n){let r=new Map;for(let{placeholder:e}of t)r.set(e,(r.get(e)??0)+1);let i=new Map;for(let[n,r]of Me(e,t))r.exact||i.set(n.placeholder,(i.get(n.placeholder)??0)+1);if(!i.size)return!1;let a=Fe(e.toString(),n);for(let[e,t]of i)if((a.get(e)??0)>(r.get(e)??0)-t)return!0;return!1}function Me(e,t){let n=new Map;for(let r of H.get(e)??[]){if(r.kind!==`range`)continue;let e=q(t,r.start);for(;t[e]?.start<r.end;){let i=t[e++],a={end:Math.min(r.end,i.end),removed:r.method===`remove`,start:Math.max(r.start,i.start)},o=n.get(i);o?o.push(a):n.set(i,[a])}}let r=new Map;for(let[e,t]of n){let n=Ne(e,t);n&&r.set(e,n)}return r}function Ne(e,t){let n=[e.start,e.end];for(let e of t)n.push(e.start,e.end);n.sort((e,t)=>e-t);let r=1;for(let e=1;e<n.length;e++)n[e]!==n[r-1]&&(n[r++]=n[e]);n.length=r;let i=new Map;for(let e=0;e<n.length;e++)i.set(n[e],e);let a=Array.from({length:n.length},(e,t)=>t),o=0;for(let e=t.length-1;e>=0;e--){let r=t[e],s=i.get(r.end),c=Pe(a,i.get(r.start));for(;c<s;)r.removed&&(o+=n[c+1]-n[c]),a[c]=Pe(a,c+1),c=a[c]}if(o)return{exact:o===e.end-e.start}}function Pe(e,t){let n=t;for(;e[n]!==n;)n=e[n];for(;e[t]!==t;){let r=e[t];e[t]=n,t=r}return n}function Fe(e,t){let n=new Map,r=new Map;for(let i of e.matchAll(V)){let a=i[0],o=t.get(a);if(o===void 0)continue;let s=r.get(a);s===void 0&&(s=J(o,a),r.set(a,s)),e.startsWith(s,i.index)&&n.set(a,(n.get(a)??0)+1)}return n}function Ie(e,t){H.get(e)?.push(t)}function G(e,t,[n,r]){Ie(e,{content:r,index:K(e,n),kind:`insert`,method:t})}function Le(e,t,n,r,i){Ie(e,{clearsInsertions:i,end:K(e,r),kind:`range`,method:t,start:K(e,n)})}function Re(e,t,n){let r=[...H.get(t)??[]],i=new Map,a=new Map;for(let e=0;e<r.length;e++){let t=r[e];if(t.kind!==`range`||!t.clearsInsertions)continue;let o=Be(n,t.start,t.end);o&&(t.start===o.start&&a.set(o.start,e),t.end===o.end&&i.set(o.end,e))}for(let t=0;t<r.length;t++){let o=r[t];if(o.kind!==`insert`||!ze(n,o.index,o.method))continue;let s=(o.method===`appendRight`||o.method===`prependRight`?a:i).get(o.index);s!==void 0&&s>t||e[o.method](o.index,o.content)}}function ze(e,t,n){if(n===`appendRight`||n===`prependRight`){let n=e[q(e,t)];return n?.start===t?n:void 0}let r=e[Ue(e,t)];return r?.end===t?r:void 0}function K(e,t){return t>=0||e.original.length===0?t:(t%e.original.length+e.original.length)%e.original.length}function Be(e,t,n){let r=e[q(e,t)];return r?.start<n?r:void 0}function Ve(e,t){let n=e[q(e,t)];return n?.start<t?n:void 0}function He(e,t){if(Ve(t,e.index))return!0;let n=q(t,e.start);for(;t[n]?.start<e.end;){let r=t[n++];if(e.start>r.start||e.end<r.end)return!0}return!1}function Ue(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;e[i].end<t?n=i+1:r=i}return n}function q(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;e[i].end<=t?n=i+1:r=i}return n}function We(e,t){if(!e.anchorsValid)return!1;let n=new Map;for(let{placeholder:e}of t)n.set(e,(n.get(e)??0)+1);for(let[t,r]of n)if((e.restoredPlaceholders.get(t)??0)<r)return!1;return!0}function J(e,t){let n=e.replace(/[^\r\n]/g,`~`),r=Ge(t);return t+n.slice(t.length,-r.length)+r}function Ge(e){return`${e.slice(3)}~*/`}function Ke(e,t){let n=new Map;for(let t of e.matchAll(Se)){let e=n.get(t[0]);e?e.push(t.index):n.set(t[0],[t.index])}let r=new Map;for(let n of e.matchAll(V)){let e=n[0],i=t.get(e);if(i===void 0)continue;let a=r.get(e);a?a.positions.push(n.index):r.set(e,{positions:[n.index],skipped:i})}let i=[],a=!0;for(let[e,{positions:t,skipped:o}]of r){let r=Ge(e),s=n.get(r)??[];t.length!==s.length&&(a=!1);let c=Math.min(t.length,s.length);for(let n=0;n<c;n++){let c=t[n],l=s[n];if(l<c+e.length||t[n+1]<l){a=!1;continue}i.push({end:l+r.length,placeholder:e,skipped:o,start:c})}}for(let e of t.keys())!r.has(e)&&(n.get(Ge(e))?.length??0)>0&&(a=!1);i.sort((e,t)=>e.start-t.start);for(let e=1;e<i.length;e++)i[e].start<i[e-1].end&&(a=!1);return{regions:i,valid:a}}function qe(e){let t=[],n=0;for(let r of e.matchAll(/\r\n|\r|\n/g))t.push({content:e.slice(n,r.index),ending:r[0],start:n}),n=r.index+r[0].length;return t.push({content:e.slice(n),ending:``,start:n}),t}function Je(e,t,n,r){let i=qe(e),a=qe(n);if(i.length!==a.length)return!1;let o=[],s=[];for(let e=0;e<i.length;e++){let n=i[e],r=a[e];if(!n.content.endsWith(r.content))return!1;let c=n.content.slice(0,n.content.length-r.content.length);if(!/^[\t ]*$/.test(c))return!1;if(c&&o.push([t+n.start,t+n.start+c.length]),n.ending!==r.ending){let e=t+n.start+n.content.length;s.push([e,e+n.ending.length,r.ending])}}for(let[e,t]of o)r.remove(e,t);for(let[e,t,n]of s)r.overwrite(e,t,n);return!0}function Ye(e){return Ce(e)?e.replace(xe,``):e}async function Xe(e,t){let n=[];for(;e.length;){let t=[...e],r=await Promise.allSettled(t),i=e.length>=t.length;for(let n=0;i&&n<t.length;n++)i=e[n]===t[n];if(i)e.copyWithin(0,t.length),e.length-=t.length;else{let n=new Map;for(let e of t)n.set(e,(n.get(e)??0)+1);let r=0;for(let t of e){let i=n.get(t);i===void 0?e[r++]=t:i===1?n.delete(t):n.set(t,i-1)}e.length=r}for(let e of r)e.status===`rejected`&&n.push(e.reason)}if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,t)}var Ze=class extends Set{target;constructor(e){super(),this.target=e}use(e){this.target=e}get size(){return this.target.size}add(e){return this.target.add(e),this}clear(){this.target.clear()}delete(e){return this.target.delete(e)}entries(){return this.target.entries()}forEach(e,t){this.target.forEach((n,r)=>e.call(t,n,r,this))}has(e){return this.target.has(e)}keys(){return this.target.keys()}values(){return this.target.values()}[Symbol.iterator](){return this.target[Symbol.iterator]()}union(e){return new Set(this).union(e)}intersection(e){return new Set(this).intersection(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}},Qe=class extends Ze{anonymousExtractions=0;interleavedAnonymousOperations=!1;recording=!0;actions=[];beginAnonymousExtraction(){this.anonymousExtractions>0&&(this.interleavedAnonymousOperations=!0),this.anonymousExtractions++}endAnonymousExtraction(){this.anonymousExtractions--}hasInterleavedAnonymousOperations(){return this.interleavedAnonymousOperations}recordInterleavedMutation(){this.anonymousExtractions>0&&(this.interleavedAnonymousOperations=!0)}use(e){this.recording=!1,super.use(e)}add(e){return this.recording&&(this.recordInterleavedMutation(),this.actions.push({token:e,type:`add`})),super.add(e)}clear(){this.recording&&(this.recordInterleavedMutation(),this.actions.push({type:`clear`})),super.clear()}delete(e){return this.recording&&(this.recordInterleavedMutation(),this.actions.push({token:e,type:`delete`})),super.delete(e)}recordExtraction(e){this.actions.push({extraction:e,type:`extract`})}async rebuildStagedTokens(e){let t=new Set;for(let n of this.actions)n.type===`add`?t.add(n.token):n.type===`delete`?t.delete(n.token):n.type===`clear`?t.clear():await e(n.extraction,t);this.target.clear();for(let e of t)this.target.add(e)}},$e=class extends a{target;constructor(e){super(),this.target=e}use(e){this.target=e}get size(){return this.target.size}clear(){this.target.clear()}delete(e){return this.target.delete(e)}entries(){return this.target.entries()}forEach(e,t){this.target.forEach((n,r)=>e.call(t,n,r,this))}get(e){return this.target.get(e)}has(e){return this.target.has(e)}keys(){return this.target.keys()}set(e,t){return this.target.set(e,t),this}values(){return this.target.values()}[Symbol.iterator](){return this.target[Symbol.iterator]()}};const et=new WeakMap;function Y(e){return et.get(e)??e}function tt(e,t){t?et.set(e,t):et.delete(e)}function nt(e,t,n,r,i){let o=`staging`,s=!1,c=t.generator,l=t.generator,u=new Set,d=new a(i),f=new Map,p=[],m=new Map,h=new Set,g=[],_=new Qe(u),v=new $e(d),y=new Ze(h),b=new $e(l.cache),x=new Ze(l.blocked),C=new $e(l.parentOrders),w=new Ze(l.activatedRules),T=new Set;function E(t){!t.active||t.dispose||(t.dispose=t.type===`invalidate`?e.onInvalidate(t.listener):e.onReload(t.listener))}function D(e,t){if(s||o===`detached`)return()=>{};let n={active:!0,listener:t,type:e};return T.add(n),o===`active`&&E(n),()=>{n.active&&(n.active=!1,n.dispose?.(),n.dispose=void 0,T.delete(n))}}let te=new Proxy(l,{get(e,t){if(t===`cache`)return b;if(t===`blocked`)return x;if(t===`parentOrders`)return C;if(t===`activatedRules`)return w;let n=Reflect.get(c,t,c);return typeof n==`function`?(...e)=>{let n=Reflect.get(c,t,c);return Reflect.apply(n,c,e)}:n},set(e,t,n){return Reflect.set(c,t,n,c)}}),O=()=>{o===`active`&&e.invalidate()},k=(t,n)=>o===`active`?e.filter(t,n):o===`staging`&&r(t,n),A=async(e,t,n)=>{let r=l.config,i=ee(r);return await l.applyExtractors(Ye(e),t,n),l.config===r&&S(i,r)?i:void 0},j=async(t,n)=>{if(o===`active`)return await e.extract(t,n);if(o===`detached`)return;if(!n){let e={code:t,extraction:void 0,id:n};_.beginAnonymousExtraction();try{e.extraction=await A(t,n,u)}finally{_.endAnonymousExtraction()}p.push(e),_.recordExtraction(e);return}let r={};if(m.set(n,r),!t){d.delete(n),f.set(n,{code:t,extraction:void 0,id:n,tokens:new Set}),m.delete(n);return}let i=new Set;try{let e=await A(t,n,i);if(m.get(n)!==r)return;d.set(n,t),f.set(n,{code:t,extraction:e,id:n,tokens:i})}finally{m.get(n)===r&&m.delete(n)}},M=async()=>await e.flushTasks(),N=()=>o===`active`?M():Xe(g,`Failed to settle staged transformer tasks`),P=Promise.resolve(n);return{context:new Proxy(e,{get(t,r,i){return r===`generator`?te:r===`tokens`?_:r===`modules`?v:r===`affectedModules`?y:r===`tasks`?o===`active`?e.tasks:g:r===`invalidate`?O:r===`filter`?k:r===`extract`?j:r===`flushTasks`?N:r===`onInvalidate`?e=>D(`invalidate`,e):r===`onReload`?e=>D(`reload`,e):r===`ready`?o===`active`?e.ready:P:r===`getConfig`?o===`active`?e.getConfig:async()=>n.config:r===`getConfigFileList`?o===`active`?e.getConfigFileList:()=>n.sources:Reflect.get(t,r,i)}}),stagedExtractions:f,stagedTokens:u,activate(){if(!s){o=`active`,c=e.generator,b.use(e.generator.cache),x.use(e.generator.blocked),C.use(e.generator.parentOrders),w.use(e.generator.activatedRules),_.use(e.tokens),v.use(e.modules),y.use(e.affectedModules);for(let e of T)E(e)}},deactivate(){if(o===`active`){o=`detached`;for(let e of T)e.dispose?.(),e.dispose=void 0;l.cache=new Map(e.generator.cache),l.blocked=new Set(e.generator.blocked),l.parentOrders=new Map(e.generator.parentOrders),l.activatedRules=new Set(e.generator.activatedRules),c=l,b.use(l.cache),x.use(l.blocked),C.use(l.parentOrders),w.use(l.activatedRules),_.use(new Set(e.tokens)),v.use(new a(e.modules)),y.use(new Set(e.affectedModules))}},detach(){if(!s){o===`active`?this.deactivate():o=`detached`,s=!0;for(let e of T)e.dispose?.();T.clear(),g.length=0}},async revalidateExtractions(){if(o!==`staging`)return;let e=[...f.values()].filter(({code:e,extraction:t})=>e&&!S(t,l.config)),t=(await Promise.allSettled(e.map(async e=>{let t=new Set,n=await A(e.code,e.id,t);if(!n)throw Error(`Candidate extractors changed while reextracting transformer-owned content`);e.extraction=n,e.tokens=t}))).filter(e=>e.status===`rejected`).map(({reason:e})=>e);if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Failed to reextract transformer-owned content`);if(p.some(({extraction:e})=>!S(e,l.config))){if(_.hasInterleavedAnonymousOperations())throw Error(`Cannot safely replay an anonymous extraction with interleaved token mutations`);await _.rebuildStagedTokens(async(e,t)=>{let n=await A(e.code,e.id,t);if(!n)throw Error(`Candidate extractors changed while reextracting anonymous transformer-owned content`);e.extraction=n})}}}}function rt(e,t){return v([...e].reverse(),(e,n)=>(n.content=t,null))}function it(e,t){let n,r=t,i=!1;return{code:e,get map(){return i||=(n=r(),r=void 0,!0),n},set map(e){n=e,r=void 0,i=!0}}}function at(e,t){return it(e,()=>new _(e).generateMap({hires:!0,includeContent:!0,source:t}))}async function X(e,t,n,r){let i=await be(e,t,n,r);if(i.length===1)throw i[0];if(i.length>1)throw AggregateError(i,`Failed to clean module "${t}"`)}async function Z(e,t,n,r){try{return await X(e,t,n,r),[]}catch(e){return e instanceof AggregateError?e.errors:[e]}}function Q(e,t,n){throw t.length?AggregateError([e,...t],e instanceof Error?e.message:n):e}function ot(e,t){return(e.generator.config.transformers??[]).filter(e=>(e.enforce||`default`)===t)}async function st(e,t,n,r){if(!t.length)return;let i=n,a,o,s,c;for(let l of t){if(l.idFilter){if(!l.idFilter(r))continue}else if(!e.filter(i,r))continue;if(!s){a??=new Map;let e=U(we(i,a),a);s=e.s,o=e.regions}let t=a;if(await l.transform(s,r,e),s.hasChanged()){let e=o;if(W(s,e))throw Error(`Failed to restore skipped source in "${r}"`);let a=s.clone();if(je(s,e,t))throw Error(`Failed to restore skipped source in "${r}"`);let l;if(Ae(s,e)){let n=Oe(s,e);if(De(a,e.filter(e=>!n.has(e)),s),l=Te(a.toString(),t),l.anchorsValid&&n.size){let r=ke(l,n,e);r.length&&(De(a,r,s),l=Te(a.toString(),t))}}else l=Te(a.toString(),t);if(!We(l,e))throw Error(`Failed to restore skipped source in "${r}"`);i=l.code;let u=l.normalizer;c??=[],c.push(()=>{let e=a.generateMap({hires:!0,source:r});return u?rt([e,u.generateMap({hires:!0,source:r})],n):e}),t.clear(),o=void 0,s=void 0}}if(i!==n)return it(i,()=>rt(c.map(e=>e()),n))}function ct(e,t,n,r){if(!n.includes(s))return st(e,t,n,r)}async function lt(e,t,n,r=`default`){let i=k(e,n,r,t),a=await L(e,n);try{if(R(e,n,i.removalVersion))return;let a=Y(e);for(;;){let o=ot(a,r),s;try{s=await ct(a,o,t,n)}catch(t){let s=await Z(o,n,a,e);if(M(e,n,r)!==i.version){let i;try{i=await ut(e,n,r)}catch(e){s.push(e)}if(i)return s.length&&Q(t,s,`Transformer phase cleanup failed for module "${n}"`),i}else try{await dt(e,n,r)}catch(e){s.push(e)}Q(t,s,`Transformer phase failed for module "${n}"`)}if(R(e,n,i.removalVersion)){await X(o,n,a,e);return}if(Y(e)===a)return M(e,n,r)===i.version?(N(e,n,r,t),s):(await X(o,n,a,e),await ut(e,n,r));await X(o,n,a,e),a=Y(e)}}finally{a.finish(),A(e,n,r)}}async function ut(e,t,n){for(;;){let r=j(e,t,n);if(r==null)return;let i=M(e,t,n),a=I(e,t),o=Y(e),s=ot(o,n),c;try{c=await ct(o,s,r,t)}catch(n){Q(n,await Z(s,t,o,e),`Failed to restore transformer phase for module "${t}"`)}if(I(e,t)!==a){await X(s,t,o,e);return}if(M(e,t,n)===i&&j(e,t,n)===r&&Y(e)===o)return N(e,t,n,r),c??at(r,t);await X(s,t,o,e)}}async function dt(e,t,n){for(;;){let r=P(e,t,n);if(r==null)return;let i=I(e,t),a=Y(e),o=ot(a,n),s;try{s=await ct(a,o,r,t)}catch(n){Q(n,await Z(o,t,a,e),`Failed to restore last successful transformer phase for module "${t}"`)}if(I(e,t)!==i){await X(o,t,a,e);return}if(P(e,t,n)===r&&Y(e)===a)return s??at(r,t);await X(o,t,a,e)}}async function ft(e,t,n){if(!e.generator.config.transformers?.length||t.includes(s))return;let r=t,i,a=[];for(let t of[`pre`,`default`,`post`]){let o=await st(e,ot(e,t),r,n);if(o&&(r=o.code,a.push(o),i=o,t!==`post`&&r.includes(s)))break}return i?it(i.code,()=>rt(a.map(({map:e})=>e),t)):void 0}async function pt(e,t){for(;;){let n=ie(e,t);if(n==null)return;let r=F(e,t),i=I(e,t),a=Y(e),o=[...a.generator.config.transformers??[]],s;try{s=await ft(a,n,t)}catch(n){Q(n,await Z(o,t,a,e),`Failed to restore transformer pipeline for module "${t}"`)}if(I(e,t)!==i){await X(o,t,a,e);return}if(F(e,t)===r&&ie(e,t)===n&&Y(e)===a){let r=s??at(n,t);return ge(e,t,r.code,n),r}await X(o,t,a,e)}}async function mt(e,t){for(;;){let n=_e(e,t);if(n==null)return;let r=I(e,t),i=Y(e),a=[...i.generator.config.transformers??[]],o;try{o=await ft(i,n,t)}catch(n){Q(n,await Z(a,t,i,e),`Failed to restore last successful transformer state for module "${t}"`)}if(I(e,t)!==r){await X(a,t,i,e);return}if(_e(e,t)===n&&Y(e)===i){let r=o??at(n,t);return ge(e,t,r.code,n),r}await X(a,t,i,e)}}async function ht(e,t,n){let r=ne(e,n,t),i=await L(e,n);try{if(R(e,n,r.removalVersion))return;F(e,n)===r.version&&ce(e,n,t);let i=Y(e);for(;;){let a=[...i.generator.config.transformers??[]],o;try{o=await ft(i,t,n)}catch(t){let o=await Z(a,n,i,e),s=!1;if(F(e,n)!==r.version){let r;try{r=await pt(e,n)}catch(e){o.push(e),s=!0}if(r)return o.length&&Q(t,o,`Transformer cleanup failed for module "${n}"`),r}else try{await mt(e,n)}catch(e){o.push(e),s=!0}if(s)try{await e.extract(``,n)}catch(e){o.push(e)}Q(t,o,`Transformer pipeline failed for module "${n}"`)}if(R(e,n,r.removalVersion)){await X(a,n,i,e);return}if(Y(e)===i)return F(e,n)===r.version?(ge(e,n,o?.code??t,t),o):(await X(a,n,i,e),await pt(e,n));await X(a,n,i,e),i=Y(e)}}finally{i.finish(),re(e,n)}}async function gt(e,t,n){return await ft(e,t,n)}const _t=p.extract;function $(e){return p.extract===_t&&e.length===1&&e[0]===p}var vt=class extends Set{added=new Set;constructor(e){super();for(let t of e)super.add(t)}add(e){return this.added.add(e),super.add(e)}},yt=class extends Set{canonical=!0;publication;get isCanonical(){return this.canonical}add(e){return this.canonical=!1,this.publication?.pendingDeletes.delete(e),this.publication?.pendingAdds.add(e),super.add(e)}clear(){if(this.canonical=!1,this.publication)for(let e of super.values())this.publication.pendingDeletes.add(e);this.publication?.pendingAdds.clear(),this.publication?.stagedTokens.clear(),super.clear()}delete(e){let t=super.delete(e),n=this.publication?.stagedTokens.delete(e)??!1,r=t||n;return r&&(this.canonical=!1,this.publication?.pendingDeletes.add(e)),this.publication?.pendingAdds.delete(e),r}beginPublication(e){if(this.publication)throw Error(`A runtime token publication is already active`);let t={baseTokens:new Set(super.values()),pendingAdds:new Set,pendingDeletes:new Set,stagedTokens:e,wasCanonical:this.canonical};this.publication=t;for(let t of e)super.add(t);return t}cancelPublication(e){if(this.publication===e){this.publication=void 0,super.clear();for(let t of e.baseTokens)super.add(t);for(let t of e.pendingAdds)super.add(t);for(let t of e.pendingDeletes)super.delete(t);this.canonical=e.pendingAdds.size||e.pendingDeletes.size?!1:e.wasCanonical}}finishPublication(e,t,n){if(this.publication!==e)throw Error(`The runtime token publication is no longer active`);let r=e.pendingAdds,i=e.pendingDeletes;this.publication=void 0,this.replaceOwned(t);for(let e of n)this.add(e);for(let e of r)this.add(e);for(let e of i)this.delete(e)}appendOwned(e){for(let t of e)super.add(t)}replaceOwned(e){let t=this.publication;super.clear();for(let n of e)for(let e of n)t?.pendingDeletes.has(e)||super.add(e);for(let e of t?.stagedTokens??[])t?.pendingDeletes.has(e)||super.add(e);for(let e of t?.pendingAdds??[])super.add(e);t||(this.canonical=!0)}};function bt(e,t){if(e.length!==t.length)return!1;let n=new Map(e.map(e=>[e.id,e]));return t.every(e=>{let t=n.get(e.id);return t!=null&&t.code===e.code&&t.content===e.content&&t.source===e.source&&t.version===e.version})}function xt(l,u={},p=()=>{}){let m,g=n.cwd(),_={},v=[],x,C=d(_,u).then(e=>(x=e,e)),w=h(b,y,{resolve:typeof l==`string`?l:g}),D=new Set,te=new Set,O=new a,k=new a,A=new WeakMap,j=new Map,M=new Map,N=new yt,P=[],ne=new Set,re=r(),F=0,ie=Promise.resolve(),I=!1,ae,L;L=De();function ce(n,r,i){let a=r;if(typeof l==`string`){let n=t(r,l);a=i[0]&&t(i[0])===n?e(n):n}return n.content?.pipeline===!1?()=>!1:h(n.content?.pipeline?.include||b,n.content?.pipeline?.exclude||y,{resolve:a})}function _e(e,t,n){return e.includes(s)?!1:e.includes(c)||e.includes(o)||n(t.replace(/[?#].*$/,``))}function z(e,t){t.length&&console.error(`[@teacss/runtime] ${e}:`,AggregateError(t,e))}function B(e,t,n=Y(m),r,i,a){return be(e,t,n,m,r,i,a)}function xe(e){let t=(j.get(e)??0)+1;j.set(e,t),O.delete(e);let n=k.delete(e);return M.delete(e),ue(m,e),ve(m,e),pe(m,e),j.get(e)===t&&j.delete(e),n}function V(){return new Set([...O.keys(),...Array.from(he(m),([e])=>e),...Array.from(fe(m),([e])=>e)])}function Se(){return Array.from(V(),e=>({code:O.get(e),content:de(m,e),id:e,source:me(m,e),version:j.get(e)??0}))}async function Ce(e,t,n,r){let i=e.generator.config,a=$(i.extractors),o=ee(i);if(await e.generator.applyExtractors(Ye(t),n,r),!(e.generator.config!==i||!S(o,i)))return a&&$(i.extractors)&&A.set(r,t),o}async function we(e,t,n,r){let i=r.map(({code:e,content:t,id:r,source:i})=>{let a=i??t??e;return a!=null&&n(a,r)}),a=nt(m,e,t,n,r.flatMap(({code:e,content:t,id:n,source:r},a)=>{let o=r??t??e;return o!=null&&i[a]?[[n,e??t??o]]:[]}));try{let t=await Promise.allSettled(r.map(async({code:t,content:n,id:r,source:o,version:s},c)=>{let l=o??n??t;if(l==null)throw Error(`Missing source for tracked module "${r}"`);let u=i[c],d=t??n??l;o!=null&&(d=(await gt(a.context,o,r))?.code??o);let f=k.get(r),p=u&&f!==void 0&&A.get(f)===d&&$(e.generator.config.extractors),m=p?f:new Set,h=p?ee(e.generator.config):void 0;return u&&!p&&(h=await Ce(e,d,r,m)),{code:t,content:n,extraction:h,id:r,included:u,next:m,output:d,source:o,version:s}})),n=[],o=[];for(let e of t)e.status===`fulfilled`?n.push(e.value):o.push(e.reason);try{await a.context.flushTasks()}catch(e){e instanceof AggregateError?o.push(...e.errors):o.push(e)}if(!o.length){let t=n.filter(t=>t.included&&!S(t.extraction,e.generator.config)),r=await Promise.allSettled([a.revalidateExtractions(),...t.map(async t=>{let n=new Set,r=await Ce(e,t.output,t.id,n);if(!r)throw Error(`Candidate extractors changed while reextracting tracked module "${t.id}"`);t.next=n,t.extraction=r})]);for(let e of r)e.status===`rejected`&&o.push(e.reason)}if(o.length===1)throw o[0];if(o.length>1)throw AggregateError(o,`Failed to stage modules during config reload`);return{nextTransformerContext:a,stagedModules:n}}catch(t){let n=new Set(r.map(({id:e})=>e));for(let e of a.stagedExtractions.keys())n.add(e);let i=await U(e.config.transformers??[],[...n],a);throw i.length?AggregateError([t,...i],`Failed to stage runtime configuration`):t}}function Te(e,t,n,r){let i=ae;try{return i?.deactivate(),r.activate(),tt(m,r.context),x.commitConfig(e)?(ae=r,_=t.config,w=n,I=!0,{committed:!0,previousTransformerContext:i}):(i?.activate(),tt(m,i?.context),{committed:!1})}catch(e){throw i?.activate(),tt(m,i?.context),e}}async function H(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=new Set,p=()=>{let e=new Set(o);for(let t of i)if(!(!t.included||f.has(t.id)))for(let n of t.next)e.add(n);for(let t of a)if(!(!t.code||f.has(t.id)))for(let n of t.next)e.add(n);l.stagedTokens.clear();for(let t of e)l.stagedTokens.add(t);N.replaceOwned(k.values())};try{let u=new Set(e.config.transformers??[]),h=r.filter(e=>!u.has(e));for(let e of i){let t=s.has(e.id)||!e.included||e.source!=null?r:h;t.length&&d.push(...await B(t,e.id,n?.context??m,c,f,p))}for(let e of i)if(!f.has(e.id)){if(e.source!=null&&ge(m,e.id,e.output,e.source),!e.included){O.delete(e.id),k.delete(e.id),M.delete(e.id),e.source??pe(m,e.id);continue}O.set(e.id,e.output),k.set(e.id,e.next),le(m,e.id,e.output)}for(let n of a)if(!f.has(n.id)){if(!n.code){se(m,n.id),xe(n.id),d.push(...await B(e.config.transformers??[],n.id,t.context,c,f,p));continue}O.set(n.id,n.code),k.set(n.id,n.next),le(m,n.id,n.code)}N.finishPublication(l,k.values(),o),W(),je()}finally{N.cancelPublication(l),n?.detach();for(let e of u)e()}z(`Post-commit module cleanup failed`,d)}async function Ee(e,t){await C;let n;try{n=await re(t,l,u)}catch(t){throw e===F&&(v=i(t)),t}if(e!==F)return n;v=n.sources,p(n);let r=[...x.config.transformers??[]];for(;e===F;){let i=await x.prepareConfig(n.config);if(e!==F)return n;let a=ce(i.config,t,n.sources),o=(e,t)=>_e(e,t,a),s=Se(),{nextTransformerContext:c,stagedModules:l}=await we(i,n,o,s),u=Array.from(c.stagedExtractions,([e,{code:t,tokens:n}])=>({code:t,id:e,next:new Set(n)})),d=Array.from(new Set([...l.map(({id:e})=>e),...u.map(({id:e})=>e)])),f=new Set(d),p=new Set(u.filter(({code:e})=>!e).map(({id:e})=>e));if(e!==F)return z(`Superseded configuration cleanup failed`,await U(i.config.transformers??[],d,c)),n;let h=await Promise.all(d.map(e=>ye(m,e)));if(!(e===F&&bt(Se(),l))){for(let e of h)e();let e=await U(i.config.transformers??[],d,c);if(e.length)throw AggregateError(e,`Failed to discard unstable runtime configuration`);continue}let g=new Set(c.stagedTokens),_=new Set(g);for(let e of l)if(e.included)for(let t of e.next)_.add(t);for(let e of u)if(e.code)for(let t of e.next)_.add(t);let v=N.beginPublication(_),y;try{y=Te(i,n,a,c)}catch(e){N.cancelPublication(v);let t;try{t=await U(i.config.transformers??[],d,c,f)}finally{for(let e of h)e()}throw t.length?AggregateError([e,...t],`Failed to commit runtime configuration`):e}if(!y.committed){N.cancelPublication(v);try{z(`Uncommitted configuration cleanup failed`,await U(i.config.transformers??[],d,c,f))}finally{for(let e of h)e()}return n}return await H(i,c,y.previousTransformerContext,r,l,u,g,p,f,v,h),n}return n}async function U(e,t,n,r){let i=[];try{for(let a of t)i.push(...await B(e,a,n.context,r))}finally{n.detach()}return i}function De(){let e=++F,t=g,n=ie.then(()=>Ee(e,t));return ie=n.then(()=>{},()=>{}),L=n,n}function Oe(){return De()}async function ke(e){return e!==g&&(g=e,Oe()),await L}function Ae(e,t){let n=[];for(let t of[...e])try{t()}catch(e){n.push(e)}z(t,n)}function W(){Ae(D,`Invalidation observer failed`)}function je(){Ae(te,`Reload observer failed`)}function Me(e,t){let n=()=>t();return e.add(n),()=>{e.delete(n)}}function Ne(){N.replaceOwned(k.values())}function Pe(e,t){if(!e||e.size!==t.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}async function Fe(e,t){if(t&&!e&&T(m,t))return;let n=t&&!e?ye(m,t):void 0;t&&n&&(E(m,t),se(m,t));let r=await C,i=Ye(e);if(t){if(!e){let e=await n;try{xe(t)&&(Ne(),W());let e=await B(r.config.transformers??[],t);z(`Module cleanup failed for "${t}"`,e)}finally{e()}return}let a=await oe(m,t);try{if(R(m,t,a.removalVersion))return;let n=(j.get(t)??0)+1;j.set(t,n);let o={};M.set(t,o);try{for(;;){let n=new Set,s=r.config,c=$(s.extractors);try{await r.applyExtractors(i,t,n)}catch(e){if(R(m,t,a.removalVersion)||M.get(t)!==o)return;if(r.config!==s)continue;throw e}if(R(m,t,a.removalVersion)||M.get(t)!==o)return;if(r.config!==s)continue;E(m,t),O.set(t,e),le(m,t,e);let l=k.get(t),u=c&&$(s.extractors);if(Pe(l,n)){u?A.set(l,e):A.delete(l);return}u&&A.set(n,e),k.set(t,n),l||!N.isCanonical?Ne():N.appendOwned(n),W();return}}finally{M.get(t)===o&&(M.delete(t),j.get(t)===n&&!O.has(t)&&de(m,t)==null&&me(m,t)==null&&j.delete(t))}}finally{a.finish()}return}let a=r.config,o=new vt(N);if(await r.applyExtractors(i,t,o),r.config!==a)return;let s=N.size;for(let e of o.added)o.has(e)&&N.add(e);N.size>s&&W()}function Ie(e,t){return _e(e,t,w)}async function G(){try{await L}catch(e){if(!I)throw e}return _}function Le(){return Xe(P,`Failed to settle runtime tasks`)}let Re=new Map;async function ze(){let e=(await G()).virtualModulePrefix||`__tea`;if(Re.has(e))return Re.get(e);let t=f(e),n={prefix:e,RESOLVED_ID_WITH_QUERY_RE:RegExp(`[/\\\\]${t}(_.*?)?\\.css(\\?.*)?$`),RESOLVED_ID_RE:RegExp(`[/\\\\]${t}(?:_(.*?))?\\.css$`)};return Re.set(e,n),n}return m={get ready(){return L},tokens:N,modules:O,affectedModules:ne,tasks:P,flushTasks:Le,invalidate:W,onInvalidate(e){return Me(D,e)},filter:Ie,reloadConfig:Oe,onReload(e){return Me(te,e)},get generator(){if(!x)throw Error("Run `await context.ready` before accessing `context.generator`");return x},extract:Fe,getConfig:G,get root(){return g},updateRoot:ke,getConfigFileList:()=>v,getVMPRegexes:ze},m}export{ht as applyTransformerPipeline,lt as applyTransformers,xt as createContext,x as defaultFilesystemGlobs,y as defaultPipelineExclude,b as defaultPipelineInclude,z as getModuleOutput};
@@ -0,0 +1,8 @@
1
+ import { GenerateOptions, GenerateResult, TeacssGenerator } from "@teacss/core";
2
+ //#region src/generation.d.ts
3
+ declare const DEFAULT_SOURCE_IGNORE: string[];
4
+ type SourceContent = string | Promise<string>;
5
+ declare function readSourceFile(file: string): Promise<string>;
6
+ declare function generateSources(generator: TeacssGenerator, files: readonly string[], sources: readonly SourceContent[], options?: GenerateOptions<false>): Promise<GenerateResult<Set<string>>>;
7
+ //#endregion
8
+ export { DEFAULT_SOURCE_IGNORE, generateSources, readSourceFile };
@@ -0,0 +1,2 @@
1
+ import{readFile as e}from"node:fs/promises";const t=[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/storybook-static/**`];async function n(t){try{return await e(t,`utf8`)}catch(e){if(e.code===`ENOENT`)return``;throw e}}function r(e,t,n){return typeof t==`string`?e.applyExtractors(t,n,new Set):t.then(t=>e.applyExtractors(t,n,new Set))}async function i(e,t,n,i){if(!t.length)return e.generate((await Promise.all(n)).join(`
2
+ `),i);let a=await Promise.all(n.map((n,i)=>r(e,n,t[i]))),o=new Set;for(let e of a)for(let t of e)o.add(t);return e.generate(o,i)}export{t as DEFAULT_SOURCE_IGNORE,i as generateSources,n as readSourceFile};
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@teacss/runtime",
3
+ "version": "0.3.0",
4
+ "description": "Build-pipeline runtime for TeaCSS (context, content extraction, transformers, layers).",
5
+ "homepage": "https://css.teasim.com",
6
+ "funding": "https://github.com/sponsors/billgo",
7
+ "license": "MIT",
8
+ "author": "Billgo <hi@billgo.me>",
9
+ "sideEffects": false,
10
+ "type": "module",
11
+ "exports": {
12
+ ".": "./dist/index.js",
13
+ "./source-generation": "./dist/source-generation.js",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "types": "./dist/index.d.ts",
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "build": "bunx rimraf dist && bunx tsdown --config tsdown.config.mts",
23
+ "dev": "tsdown --watch"
24
+ },
25
+ "dependencies": {
26
+ "@jridgewell/remapping": "^2.3.5",
27
+ "@teacss/config": "0.3.0",
28
+ "@teacss/core": "0.3.0",
29
+ "magic-string": "^1.1.0",
30
+ "unplugin-utils": "^0.3.2"
31
+ },
32
+ "devDependencies": {
33
+ "@jridgewell/trace-mapping": "^0.3.31"
34
+ },
35
+ "engines": {
36
+ "node": ">=22.12.0"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
41
+ }