@nstudio/nativescript-compiler-effect-ui 0.0.0-stage → 9.2.0-alpha.21

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,19 @@
1
+ Copyright OpenJS Foundation and other contributors, https://openjsf.org
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @nstudio/nativescript-compiler-effect-ui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Effect UI (`@effect/ui` + `effect` v4) framework adapter for [`@nstudio/nativescript-compiler`](../compiler).
4
+
5
+ Compiles NativeScript apps written with Effect UI (including `MasonHost`, `NativeHost`, `@effect/ui`, `@effect/ui-kit`, and `effect` v4) directly to native Swift (iOS) and Kotlin (Android) with no JavaScript runtime.
@@ -0,0 +1,8 @@
1
+ /** The compiler's own functions and state, from the compiler that loaded the adapter: set by its entry before any front end runs. */
2
+ export let core;
3
+ /** The compiler's TypeScript (`core.ts`), set with `core`: the adapter reads and makes the compiler's syntax trees with it, never with a TypeScript of its own. */
4
+ export let ts;
5
+ export function useCore(api) {
6
+ core = api;
7
+ ts = api.ts;
8
+ }
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ import { useCore } from "./core-api.js";
2
+ import { transformEffectSource } from "./transform.js";
3
+ export default function adapter(core) {
4
+ useCore(core);
5
+ return {
6
+ apiVersion: 1,
7
+ name: 'effect-ui',
8
+ // Effect and @effect/ui are pure TypeScript and compile directly from their shipped sources.
9
+ packages: [],
10
+ behaviour: {
11
+ schedule: 'now',
12
+ eventScope: 'none',
13
+ propsOrder: 'pre',
14
+ deferBindings: false,
15
+ insertion: 'built',
16
+ listenersAfterBindings: false,
17
+ effectScope: null,
18
+ checkEveryBinding: 'off',
19
+ slots: false,
20
+ rowSignals: 'off',
21
+ fragments: false,
22
+ },
23
+ reach: 'entry',
24
+ modules: {
25
+ transformSource: transformEffectSource,
26
+ },
27
+ frontEnd(app) {
28
+ // Pure TypeScript app: the entry calls Application.run / MasonHost.run / NativeHost.run directly.
29
+ return {
30
+ components: [],
31
+ modules: [...app.sources, app.entry],
32
+ root: '',
33
+ mounted: true,
34
+ };
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,625 @@
1
+ import { ts } from "./core-api.js";
2
+ function applyEdits(text, edits) {
3
+ if (!edits.length)
4
+ return text;
5
+ let out = text;
6
+ for (const e of [...edits].sort((a, b) => b.start - a.start)) {
7
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
8
+ }
9
+ return out;
10
+ }
11
+ function preserveLines(orig, replacement) {
12
+ const origLines = (orig.match(/\n/g) ?? []).length;
13
+ const newLines = (replacement.match(/\n/g) ?? []).length;
14
+ return replacement + (origLines > newLines ? '\n'.repeat(origLines - newLines) : '');
15
+ }
16
+ /**
17
+ * Lowers Effect v4 and `@effect/ui` TypeScript idioms into static forms that
18
+ * `@nstudio/nativescript-compiler`'s Swift and Kotlin backends compile directly:
19
+ *
20
+ * 1. `class Foo extends (Context|Command|Query).Service<...>()(...) { static ... }`
21
+ * -> nominal `interface Foo` + `const Foo = ...` singleton with static members attached.
22
+ * 2. `class Foo extends (Data.)?TaggedError("Tag")<Fields>` and
23
+ * `class Foo extends (Data.)?TaggedClass("Tag")<Fields>`
24
+ * -> concrete subclasses of `Data.Error` / `Data.Class` with typed stored fields.
25
+ * 3. Effect & `@effect/ui` library internals that rely on dynamic JS-engine idioms
26
+ * (`Pipeable.Class` / `YieldableError` IIFEs, `Function.dual` `arguments`,
27
+ * `Reflect.ownKeys` / `Reflect.get`, `SharedArrayBuffer` guards, local service
28
+ * subclasses inside factories, `new Array(n)` untyped slots).
29
+ */
30
+ export function transformEffectSource(code, fileName) {
31
+ const norm = fileName.replace(/\\/g, '/');
32
+ let out = code;
33
+ if (norm.includes('/effect/src/'))
34
+ out = transformEffectLib(out, norm);
35
+ else if (norm.includes('/@effect/ui/src/'))
36
+ out = transformEffectUiLib(out, norm);
37
+ else if (norm.includes('/nativescript-masonkit/')) {
38
+ if (out.includes('NativeScript.Mason')) {
39
+ // Windows-only dead code inside shared masonkit common.ts (`_windowsCreateAnonymousText`, `windowsBreakRun`)
40
+ out = out.replace(/\bnew NativeScript\.Mason\.\w+\([^)]*\)/g, '(undefined as any)').replace(/\bNativeScript\.Mason\.\w+/g, 'any');
41
+ }
42
+ if (/\/nativescript-masonkit\/common\.(?:ts|js)$/.test(norm)) {
43
+ // `objc!Mason.d.ts` omits `setMeasureForViewBlock`, `mason_addEventListener`, and `mason_removeEventListenerId`
44
+ // even though `Mason-Swift.h` exports them with ObjC block parameters; typing the receivers lets Swift emit
45
+ // direct typed ObjC-block calls instead of dynamic `objc_msgSend` (which skips `@?` block arguments).
46
+ const decls = [];
47
+ if (out.includes('setMeasureForViewBlock')) {
48
+ decls.push('interface NSCMason { setMeasureForViewBlock(view: any, block: (knownW: number, knownH: number, availW: number, availH: number) => any): void; }');
49
+ out = out.replace(/const mason = native\?\.mason \?\? native\?\.node\?\.mason;\s*if \(typeof mason\?\.setMeasureForViewBlock !== 'function'\) return;/, 'const mason = (native?.mason ?? native?.node?.mason) as NSCMason | undefined;\n if (!mason) return;');
50
+ }
51
+ if (out.includes('mason_addEventListener')) {
52
+ decls.push('interface NSObject { mason_addEventListener(event: string, listener: (event: any) => void): any; mason_removeEventListenerId(event: string, id: any): boolean; }');
53
+ out = out
54
+ .replace(/this\._view\.mason_addEventListener\(/g, '(this._view as NSObject).mason_addEventListener(')
55
+ .replace(/this\._view\.mason_removeEventListenerId\(/g, '(this._view as NSObject).mason_removeEventListenerId(');
56
+ }
57
+ if (decls.length) {
58
+ out = `declare global { ${decls.join(' ')} }\n` + out;
59
+ }
60
+ }
61
+ if (/\/nativescript-masonkit\/style\.(?:ts|js)$/.test(norm)) {
62
+ out = out
63
+ .replace(/private view_: View;/, 'private view_: any;')
64
+ .replace(/static fromView\(view: View, nativeView\)/, 'static fromView(view: any, nativeView)')
65
+ .replace(/static fromPseudo\(pseudo: string, view: View, nativeView\)/, 'static fromPseudo(pseudo: string, view: any, nativeView)')
66
+ .replace(/get view\(\): View \{/, 'get view(): any {')
67
+ .replace(/\{\s*\.\.\.coreLayout,\s*\.\.\.masonLayout\s*\}/, '{ toDevicePixels: coreLayout.toDevicePixels, toDeviceIndependentPixels: coreLayout.toDeviceIndependentPixels, getDisplayDensity: coreLayout.getDisplayDensity, makeMeasureSpec: coreLayout.makeMeasureSpec, getMeasureSpecMode: coreLayout.getMeasureSpecMode, getMeasureSpecSize: coreLayout.getMeasureSpecSize, round: coreLayout.round, ...masonLayout }');
68
+ }
69
+ }
70
+ else if (norm.includes('/nativescript-effect-ui/')) {
71
+ if (out.includes("import('@nativescript/core')")) {
72
+ out =
73
+ `import { Application, Utils } from '@nativescript/core';\n` +
74
+ out
75
+ .replace(/void import\('@nativescript\/core'\)\.then\(\(\{\s*Application,\s*Utils\s*\}\)\s*=>\s*\{/g, 'void Promise.resolve().then(() => {')
76
+ .replace(/const\s*\{\s*Application,\s*Utils\s*\}\s*=\s*yield\*\s*Effect\.promise\(\(\)\s*=>\s*import\('@nativescript\/core'\)\);/g, '')
77
+ .replace(/import\('@nativescript\/core'\)/g, 'Promise.resolve({ Application, Utils })');
78
+ }
79
+ if (norm.endsWith('/native/Native.ts')) {
80
+ out = out.replace(/Record<string,\s*NativeElement<any,\s*any,\s*any,\s*any,\s*any>>/g, 'Record<string, any>');
81
+ }
82
+ if (norm.endsWith('/platform/intl.ts')) {
83
+ // V8-without-ICU polyfill (`Date.prototype` / `Number.prototype` monkey-patching) is unnecessary under native Swift/Kotlin compilation.
84
+ return `export interface IntlBackend {}\nexport interface IntlPolyfillTarget {}\nexport interface IntlPolyfillReport { readonly dateTimeFormat: boolean; readonly numberFormat: boolean; readonly dateToLocale: boolean; readonly numberToLocale: boolean; }\nexport function createIntlPolyfill(_backend: IntlBackend): any { return {}; }\nexport function installIntlPolyfillWith(_backend: IntlBackend, _options?: any): IntlPolyfillReport { return { dateTimeFormat: false, numberFormat: false, dateToLocale: false, numberToLocale: false }; }\nexport function installIntlPolyfill(): void {}\n`;
85
+ }
86
+ if (norm.endsWith('/platform/intl-mapping.ts')) {
87
+ out = out.replace(/\bObject\(options\)/g, '(typeof options === "object" && options !== null ? options : {})');
88
+ }
89
+ if (norm.endsWith('/mason/svg.ts')) {
90
+ const cut = out.indexOf('\nconst isApple = (): boolean =>');
91
+ if (cut >= 0) {
92
+ out =
93
+ out.slice(0, cut) +
94
+ `\n@CSSType('svg')\nclass MasonSvgElement extends Div {\n _svgTree: SvgNode | undefined;\n setSvgTree(root: SvgNode): void {\n this._svgTree = root;\n }\n}\nexport function createSvgElementClass(): ElementConstructor {\n return MasonSvgElement as unknown as ElementConstructor;\n}\n`;
95
+ }
96
+ }
97
+ if (norm.endsWith('/mason/video.ts')) {
98
+ const cut = out.indexOf('\nconst isApple = (): boolean =>');
99
+ if (cut >= 0) {
100
+ out =
101
+ out.slice(0, cut) +
102
+ `\n@CSSType('video')\nclass MasonVideoElement extends Div {\n setSources(_sources: ReadonlyArray<VideoSource>): void {}\n play(): void {}\n pause(): void {}\n}\nexport function createVideoElementClass(): ElementConstructor {\n return MasonVideoElement as unknown as ElementConstructor;\n}\n`;
103
+ }
104
+ }
105
+ if (norm.endsWith('/mason/elements.ts')) {
106
+ out = out
107
+ .replace(/class MasonAnchor extends \(A as unknown as new \(\) => NSView & \{ followHref: \(\) => void \}\) \{/, 'class MasonAnchor extends A {')
108
+ .replace(/CSSType\('a'\)\(MasonAnchor\);/, '')
109
+ .replace(/function makeBlockElement\(tag: string\): ElementConstructor \{\s*class MasonBlockElement extends Div \{\}\s*CSSType\(tag\)\(MasonBlockElement\);\s*return MasonBlockElement as unknown as ElementConstructor;\s*\}/, `function makeBlockElement(_tag: string): ElementConstructor {\n return Div as unknown as ElementConstructor;\n}`);
110
+ }
111
+ if (norm.endsWith('/mason/input-native.ts')) {
112
+ return `import type { View as NSView } from '@nativescript/core';\nexport interface NativeInputHooks { readonly onEdit: () => void; readonly onReturn: () => void; }\nexport function syncNativeInput(_view: NSView, _tag: string): void {}\nexport function setNativeInputHooks(_view: NSView, _tag: string, _hooks: NativeInputHooks): void {}\nexport function dismissKeyboard(): void {}\nexport function installTapToDismissKeyboard(_view: NSView): () => void { return () => {}; }\n`;
113
+ }
114
+ }
115
+ if (/\bclass\b/.test(out)) {
116
+ out = transformEffectClasses(out, fileName);
117
+ }
118
+ return out;
119
+ }
120
+ /** Rewrites `this` and value references to `className` inside a static initializer/method to `selfName`. */
121
+ function rewriteStaticSelf(exprText, className, selfName, rewriteThis) {
122
+ const sf = ts.createSourceFile('__expr.ts', `const __e = (${exprText});`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
123
+ const offset = 'const __e = ('.length;
124
+ const edits = [];
125
+ const isTypePosition = (n) => {
126
+ for (let p = n.parent; p; p = p.parent) {
127
+ if (ts.isTypeNode(p) || ts.isTypeParameterDeclaration(p))
128
+ return true;
129
+ if (ts.isExpressionWithTypeArguments(p) && p.expression === n)
130
+ return false;
131
+ }
132
+ return false;
133
+ };
134
+ const isPropertyName = (id) => {
135
+ const p = id.parent;
136
+ if (!p)
137
+ return false;
138
+ if (ts.isPropertyAccessExpression(p) && p.name === id)
139
+ return true;
140
+ if ((ts.isPropertyAssignment(p) || ts.isPropertyDeclaration(p) || ts.isMethodDeclaration(p) || ts.isGetAccessorDeclaration(p) || ts.isSetAccessorDeclaration(p)) && p.name === id)
141
+ return true;
142
+ if ((ts.isVariableDeclaration(p) || ts.isParameter(p) || ts.isFunctionDeclaration(p) || ts.isClassDeclaration(p) || ts.isBindingElement(p)) && p.name === id)
143
+ return true;
144
+ return false;
145
+ };
146
+ const visit = (n, nestedFn) => {
147
+ if (rewriteThis && !nestedFn && n.kind === ts.SyntaxKind.ThisKeyword) {
148
+ edits.push({ start: n.getStart(sf) - offset, end: n.getEnd() - offset, text: selfName });
149
+ return;
150
+ }
151
+ if (ts.isIdentifier(n) && n.text === className && !isPropertyName(n) && !isTypePosition(n)) {
152
+ if (ts.isShorthandPropertyAssignment(n.parent) && n.parent.name === n) {
153
+ edits.push({ start: n.getStart(sf) - offset, end: n.getEnd() - offset, text: `${className}: ${selfName}` });
154
+ }
155
+ else {
156
+ edits.push({ start: n.getStart(sf) - offset, end: n.getEnd() - offset, text: selfName });
157
+ }
158
+ return;
159
+ }
160
+ const nextNested = nestedFn || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n) || ts.isClassLike(n) || ts.isMethodDeclaration(n);
161
+ ts.forEachChild(n, (c) => visit(c, nextNested));
162
+ };
163
+ visit(sf, false);
164
+ return applyEdits(exprText, edits);
165
+ }
166
+ /** Recognizes `Context.Service<...>()(...)`, `Command.Service<...>()(...)`, `Query.Service<...>()(...)`. */
167
+ function isEffectServiceBase(expr) {
168
+ if (!ts.isCallExpression(expr))
169
+ return false;
170
+ const inner = expr.expression;
171
+ if (!ts.isCallExpression(inner))
172
+ return false;
173
+ const callee = inner.expression;
174
+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'Service' && ts.isIdentifier(callee.expression)) {
175
+ return ['Context', 'Command', 'Query'].includes(callee.expression.text);
176
+ }
177
+ return false;
178
+ }
179
+ /** Recognizes `(Data.)?TaggedError("Tag")` or `(Data.)?TaggedClass("Tag")` in a class `extends` clause. */
180
+ function matchTaggedBase(heritage, _sf) {
181
+ const expr = heritage.expression;
182
+ if (!ts.isCallExpression(expr) || expr.arguments.length !== 1 || !ts.isStringLiteralLike(expr.arguments[0]))
183
+ return null;
184
+ const tag = expr.arguments[0].text;
185
+ const callee = expr.expression;
186
+ let prefix = '';
187
+ let fnName = '';
188
+ if (ts.isIdentifier(callee)) {
189
+ fnName = callee.text;
190
+ }
191
+ else if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
192
+ prefix = `${callee.expression.text}.`;
193
+ fnName = callee.name.text;
194
+ }
195
+ if (fnName !== 'TaggedError' && fnName !== 'TaggedClass')
196
+ return null;
197
+ const fieldsNode = heritage.typeArguments?.[0];
198
+ return { kind: fnName === 'TaggedError' ? 'error' : 'class', prefix, tag, fieldsNode };
199
+ }
200
+ function extractLiteralFields(typeNode, sf) {
201
+ if (!typeNode || !ts.isTypeLiteralNode(typeNode))
202
+ return [];
203
+ const out = [];
204
+ for (const m of typeNode.members) {
205
+ if (!ts.isPropertySignature(m) || !(ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)))
206
+ continue;
207
+ const name = m.name.text;
208
+ if (name === '_tag')
209
+ continue;
210
+ out.push({ name, optional: !!m.questionToken, typeText: m.type ? m.type.getText(sf) : 'any' });
211
+ }
212
+ return out;
213
+ }
214
+ function transformEffectClasses(code, fileName) {
215
+ const sf = ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest, true, fileName.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
216
+ const edits = [];
217
+ const extraImports = [];
218
+ const importedFrom = (symbolName) => {
219
+ for (const s of sf.statements) {
220
+ if (!ts.isImportDeclaration(s) || !ts.isStringLiteral(s.moduleSpecifier))
221
+ continue;
222
+ const bindings = s.importClause?.namedBindings;
223
+ if (bindings && ts.isNamedImports(bindings)) {
224
+ for (const el of bindings.elements) {
225
+ if (el.name.text === symbolName)
226
+ return s.moduleSpecifier.text;
227
+ }
228
+ }
229
+ }
230
+ return 'effect/Data';
231
+ };
232
+ const addedImports = new Set();
233
+ const ensureBaseImport = (kind) => {
234
+ const alias = kind === 'error' ? '__EffectDataError' : '__EffectDataClass';
235
+ const exportName = kind === 'error' ? 'Error' : 'Class';
236
+ const fromSpec = importedFrom(kind === 'error' ? 'TaggedError' : 'TaggedClass');
237
+ const key = `${exportName}:${fromSpec}`;
238
+ if (!addedImports.has(key)) {
239
+ addedImports.add(key);
240
+ extraImports.push(`import { ${exportName} as ${alias} } from ${JSON.stringify(fromSpec)};`);
241
+ }
242
+ return alias;
243
+ };
244
+ const interfacesInFile = new Set();
245
+ for (const st of sf.statements) {
246
+ if (ts.isInterfaceDeclaration(st))
247
+ interfacesInFile.add(st.name.text);
248
+ }
249
+ for (const st of sf.statements) {
250
+ // 0. `export const Foo: new(...) => Foo = class [extends Base] { ... }` paired with `export interface Foo` -> `export class Foo [extends Base] { ... }`
251
+ if (ts.isVariableStatement(st) && st.declarationList.declarations.length === 1) {
252
+ const decl = st.declarationList.declarations[0];
253
+ if (ts.isIdentifier(decl.name) && interfacesInFile.has(decl.name.text) && decl.type && ts.isConstructorTypeNode(decl.type) && decl.initializer) {
254
+ let initExpr = decl.initializer;
255
+ while (ts.isAsExpression(initExpr) || ts.isParenthesizedExpression(initExpr))
256
+ initExpr = initExpr.expression;
257
+ if (ts.isClassExpression(initExpr)) {
258
+ const exported = !!ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
259
+ const expPrefix = exported ? 'export ' : '';
260
+ const clsName = decl.name.text;
261
+ const orig = code.slice(st.getStart(sf), st.getEnd());
262
+ const ext = initExpr.heritageClauses?.map((h) => h.getText(sf)).join(' ');
263
+ const bodyStart = code.indexOf('{', initExpr.getStart(sf));
264
+ const bodyText = code.slice(bodyStart, initExpr.getEnd());
265
+ const rep = `${expPrefix}class ${clsName}${ext ? ` ${ext}` : ''} ${bodyText}`;
266
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, rep) });
267
+ continue;
268
+ }
269
+ }
270
+ }
271
+ if (!ts.isClassDeclaration(st) || !st.name)
272
+ continue;
273
+ const ext = st.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
274
+ if (!ext)
275
+ continue;
276
+ const className = st.name.text;
277
+ const exported = !!ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
278
+ const expPrefix = exported ? 'export ' : '';
279
+ const orig = code.slice(st.getStart(sf), st.getEnd());
280
+ // 1. Service classes (`Context.Service` / `Command.Service` / `Query.Service`)
281
+ if (isEffectServiceBase(ext.expression)) {
282
+ const hasInstance = st.members.some((m) => ts.isConstructorDeclaration(m) || !ts.canHaveModifiers(m) || !ts.getModifiers(m)?.some((mod) => mod.kind === ts.SyntaxKind.StaticKeyword));
283
+ if (hasInstance)
284
+ continue;
285
+ const baseExprText = ext.expression.getText(sf);
286
+ if (st.members.length === 0) {
287
+ const rep = `${expPrefix}interface ${className} { readonly __nsEffectServiceBrand?: ${JSON.stringify(className)} }\n${expPrefix}const ${className} = ${baseExprText};`;
288
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, rep) });
289
+ continue;
290
+ }
291
+ const methodEntries = [];
292
+ const fieldInits = [];
293
+ const fieldEntries = [];
294
+ let fieldIdx = 0;
295
+ for (const m of st.members) {
296
+ if (ts.isMethodDeclaration(m) && m.name) {
297
+ const nameText = m.name.getText(sf);
298
+ const params = m.parameters.map((p) => p.getText(sf)).join(', ');
299
+ const tparams = m.typeParameters ? `<${m.typeParameters.map((tp) => tp.getText(sf)).join(', ')}>` : '';
300
+ const ret = m.type ? `: ${m.type.getText(sf)}` : '';
301
+ const body = m.body ? rewriteStaticSelf(m.body.getText(sf), className, '__self', false) : '{}';
302
+ methodEntries.push(`${nameText}${tparams}(${params})${ret} ${body}`);
303
+ }
304
+ else if (ts.isGetAccessorDeclaration(m) && m.name) {
305
+ const nameText = m.name.getText(sf);
306
+ const ret = m.type ? `: ${m.type.getText(sf)}` : '';
307
+ const body = m.body ? rewriteStaticSelf(m.body.getText(sf), className, '__self', false) : '{}';
308
+ methodEntries.push(`get ${nameText}()${ret} ${body}`);
309
+ }
310
+ else if (ts.isPropertyDeclaration(m) && m.name) {
311
+ const nameText = m.name.getText(sf);
312
+ const varName = `__f${fieldIdx++}`;
313
+ const typeAnn = m.type ? `: ${m.type.getText(sf)}` : '';
314
+ const initText = m.initializer ? rewriteStaticSelf(m.initializer.getText(sf), className, '__self', true) : 'undefined';
315
+ fieldInits.push(`const ${varName}${typeAnn} = ${initText};`);
316
+ fieldEntries.push(`${nameText}: ${varName}`);
317
+ }
318
+ }
319
+ const parts = [
320
+ `${expPrefix}interface ${className} { readonly __nsEffectServiceBrand?: ${JSON.stringify(className)} }`,
321
+ `${expPrefix}const ${className} = (() => {`,
322
+ ` const __base = ${baseExprText};`,
323
+ methodEntries.length ? ` const __self = Object.assign(__base, { ${methodEntries.join(', ')} });` : ` const __self = __base;`,
324
+ ...fieldInits.map((l) => ` ${l}`),
325
+ fieldEntries.length ? ` return Object.assign(__self, { ${fieldEntries.join(', ')} });` : ` return __self;`,
326
+ `})();`,
327
+ ];
328
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, parts.join('\n')) });
329
+ continue;
330
+ }
331
+ // 2. TaggedError / TaggedClass subclasses
332
+ const tagged = matchTaggedBase(ext, sf);
333
+ if (tagged) {
334
+ const baseCtor = tagged.prefix ? `${tagged.prefix}${tagged.kind === 'error' ? 'Error' : 'Class'}` : ensureBaseImport(tagged.kind);
335
+ const fields = extractLiteralFields(tagged.fieldsNode, sf);
336
+ const hasCtor = st.members.some(ts.isConstructorDeclaration);
337
+ const existingFields = new Set(st.members
338
+ .filter((m) => ts.isPropertyDeclaration(m) && (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)))
339
+ .map((m) => (ts.isIdentifier(m.name) ? m.name.text : m.name.getText(sf).slice(1, -1))));
340
+ const declLines = [` readonly _tag = ${JSON.stringify(tagged.tag)} as const;`];
341
+ if (tagged.kind === 'error')
342
+ declLines.push(` override name = ${JSON.stringify(tagged.tag)};`);
343
+ for (const f of fields) {
344
+ if (existingFields.has(f.name))
345
+ continue;
346
+ declLines.push(` readonly ${f.name}${f.optional ? '?' : '!'}: ${f.typeText};`);
347
+ }
348
+ if (!hasCtor && fields.length > 0) {
349
+ const argType = tagged.fieldsNode.getText(sf);
350
+ const assigns = fields.map((f) => ` (this as any).${f.name} = (args as any).${f.name};`).join('\n');
351
+ declLines.push(` constructor(args: ${argType}) {\n super(args as any);\n if (args) {\n${assigns}\n }\n }`);
352
+ }
353
+ else if (!hasCtor) {
354
+ declLines.push(` constructor(args?: any) { super(args); }`);
355
+ }
356
+ const bodyStart = code.indexOf('{', ext.getEnd());
357
+ const bodyInner = code.slice(bodyStart + 1, st.getEnd() - 1);
358
+ const typeArgs = tagged.fieldsNode ? `<${tagged.fieldsNode.getText(sf)}>` : '';
359
+ const rep = `${expPrefix}class ${className} extends ${baseCtor}${typeArgs} {\n${declLines.join('\n')}\n${bodyInner}}`;
360
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, rep) });
361
+ }
362
+ }
363
+ const result = applyEdits(code, edits);
364
+ return extraImports.length ? `${extraImports.join('\n')}\n${result}` : result;
365
+ }
366
+ /** Targeted static lowerings for `effect/src/` modules so unmodified `effect@4.x` compiles natively. */
367
+ function transformEffectLib(code, norm) {
368
+ if (norm.endsWith('/effect/src/Pipeable.ts')) {
369
+ return code.replace(/export const Class: new\(\) => Pipeable = \(function\(\) \{\s*function PipeableBase\(\) \{\}\s*PipeableBase\.prototype = Prototype\s*return PipeableBase as any\s*\}\)\(\)/, `export class Class implements Pipeable {\n pipe(...args: ReadonlyArray<any>): any {\n return pipeArguments(this, args as any)\n }\n}`);
370
+ }
371
+ if (norm.endsWith('/effect/src/Data.ts')) {
372
+ let out = code.replace(/export const Class: new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A\]: A\[P\] \}>\s*\) => Readonly<A> & Pipeable\.Pipeable = class extends Pipeable\.Class \{\s*constructor\(props: object \| undefined\) \{\s*super\(\)\s*if \(props\) \{\s*InternalRecord\.assignProperties\(this, props\)\s*\}\s*\}\s*\} as any/, `export class Class<A extends Record<string, any> = {}> extends Pipeable.Class {\n constructor(args?: Types.VoidIfEmpty<{ readonly [P in keyof A]: A[P] }>) {\n super()\n if (args) {\n InternalRecord.assignProperties(this, args as any)\n }\n }\n}`);
373
+ out = out.replace(/export const TaggedClass = <Tag extends string>\(\s*tag: Tag\s*\): new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A as P extends "_tag" \? never : P\]: A\[P\] \}>\s*\) => Readonly<A> & \{ readonly _tag: Tag \} & Pipeable\.Pipeable =>\s*class extends Class \{\s*readonly _tag = tag\s*\} as any/, `export const TaggedClass = <Tag extends string>(tag: Tag): new<A extends Record<string, any> = {}>(args: Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P] }>) => Readonly<A> & { readonly _tag: Tag } & Pipeable.Pipeable => Class as any`);
374
+ out = out.replace(/export const Error: new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A\]: A\[P\] \}>\s*\) => Cause\.YieldableError & Readonly<A> = core\.Error/, `export { Error } from "./internal/core.ts"`);
375
+ return out;
376
+ }
377
+ if (norm.endsWith('/effect/src/internal/core.ts')) {
378
+ let out = code;
379
+ out = out.replace(/export const YieldableError: new\(\s*message\?: string,\s*options\?: ErrorOptions\s*\) => Cause\.YieldableError = \(function\(\) \{\s*class YieldableError extends globalThis\.Error \{\}\s*const proto = makePrimitiveProto\(\{\s*op: "YieldableError",\s*\[evaluate\]\(\) \{\s*return exitFail\(this\)\s*\}\s*\}\)\s*delete \(proto as any\)\.toString\s*Object\.assign\(\s*YieldableError\.prototype,\s*proto\s*\)\s*return YieldableError as any\s*\}\)\(\)/, `export class YieldableError extends globalThis.Error {\n constructor(message?: string, options?: ErrorOptions) { super(message, options) }\n pipe(...args: ReadonlyArray<any>): any { return pipeArguments(this, args as any) }\n [Symbol.iterator](): any { return new SingleShotGen(this) }\n}\nconst __yeProto = makePrimitiveProto({ op: "YieldableError", [evaluate]() { return exitFail(this) } })\ndelete (__yeProto as any).toString\nObject.assign(YieldableError.prototype, __yeProto)`);
380
+ out = out.replace(/export const Error: new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A\]: A\[P\] \}>\s*\) => Cause\.YieldableError & Readonly<A> = \(function\(\) \{\s*const plainArgsSymbol = Symbol\.for\("effect\/Data\/Error\/plainArgs"\)\s*return class Base extends YieldableError \{\s*constructor\(args: Record<string, any> \| undefined\) \{\s*super\(args\?\.message, args\?\.cause \? \{ cause: args\.cause \} : undefined\)\s*if \(args\) \{\s*InternalRecord\.assignProperties\(this, args\)\s*\/\/ @effect-diagnostics-next-line floatingEffect:off\s*Object\.defineProperty\(this, plainArgsSymbol, \{\s*value: args,\s*enumerable: false\s*\}\)\s*\}\s*\}\s*override toJSON\(\) \{\s*return \{ \.\.\.\(this as any\)\[plainArgsSymbol\], \.\.\.this \}\s*\}\s*\} as any\s*\}\)\(\)/, `const __plainArgsSymbol = Symbol.for("effect/Data/Error/plainArgs")\nexport class Error<A extends Record<string, any> = {}> extends YieldableError {\n constructor(args?: Types.VoidIfEmpty<{ readonly [P in keyof A]: A[P] }>) {\n const a = args as Record<string, any> | undefined\n super(a?.message, a?.cause ? { cause: a.cause } : undefined)\n if (a) {\n InternalRecord.assignProperties(this, a)\n Object.defineProperty(this, __plainArgsSymbol, { value: a, enumerable: false })\n }\n }\n toJSON(): any {\n return { ...(this as any)[__plainArgsSymbol], ...this }\n }\n}`);
381
+ out = out.replace(/export const TaggedError = <Tag extends string>\(\s*tag: Tag\s*\): new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A as P extends "_tag" \? never : P\]: A\[P\] \}>\s*\) => Cause\.YieldableError & \{ readonly _tag: Tag \} & Readonly<A> => \{\s*class Base extends Error<\{\}> \{\s*readonly _tag = tag\s*\}\s*;\(Base\.prototype as any\)\.name = tag\s*return Base as any\s*\}/, `export const TaggedError = <Tag extends string>(tag: Tag): new<A extends Record<string, any> = {}>(args: Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P] }>) => Cause.YieldableError & { readonly _tag: Tag } & Readonly<A> => Error as any`);
382
+ out = out.replace(/const self = Object\.assign\(Object\.create\(Object\.getPrototypeOf\(this\)\), this\)\s*self\.annotations = newAnnotations/, `const self: any = this._tag === "Fail" ? new Fail((this as any).error, newAnnotations) : this._tag === "Die" ? new Die((this as any).defect, newAnnotations) : Object.assign(Object.create(Object.getPrototypeOf(this)), this)\n self.annotations = newAnnotations`);
383
+ return out;
384
+ }
385
+ if (norm.endsWith('/effect/src/Function.ts')) {
386
+ let out = code;
387
+ out = out.replace(/<DataLast extends \(\.\.\.args: Array<any>\) => any, DataFirst extends \(\.\.\.args: Array<any>\) => any>\(/g, '<DataLast = any, DataFirst = any>(');
388
+ out = out.replace(/arity: Parameters<DataFirst>\["length"\], body: DataFirst/g, 'arity: any, body: DataFirst');
389
+ out = out.replace(/isDataFirst: \(args: IArguments\) => boolean, body: DataFirst/g, 'isDataFirst: (args: any) => boolean, body: DataFirst');
390
+ out = out.replace(/if \(typeof arity === "function"\) \{\s*return function\(this: any\) \{\s*return arity\(arguments\)\s*\? body\.apply\(this, arguments as any\)\s*: \(\(self: any\) => body\(self, \.\.\.arguments\)\) as any\s*\}\s*\}/, `if (typeof arity === "function") {\n return function(this: any, ...__args: Array<any>) {\n return arity(__args as any)\n ? body.apply(this, __args as any)\n : ((self: any) => body(self, ...__args)) as any\n }\n }`);
391
+ out = out.replace(/default:\s*return function\(\) \{\s*if \(arguments\.length >= arity\) \{\s*\/\/ @ts-expect-error\s*return body\.apply\(this, arguments\)\s*\}\s*const args = arguments\s*return function\(self: any\) \{\s*return body\(self, \.\.\.args\)\s*\}\s*\}/, `default:\n return function(this: any, ...args: Array<any>) {\n if (args.length >= arity) {\n return body.apply(this, args as any)\n }\n return function(self: any) {\n return body(self, ...args)\n }\n }`);
392
+ return out;
393
+ }
394
+ if (norm.endsWith('/effect/src/Formatter.ts')) {
395
+ return code
396
+ .replace(/return Reflect\.ownKeys\(o\)/g, 'return [...Object.getOwnPropertyNames(o), ...Object.getOwnPropertySymbols(o)]')
397
+ .replace(/v\["toString"\] !== Array\.prototype\.toString/g, 'v["toString"] !== ([] as any).toString')
398
+ .replace(/const value = Reflect\.get\(object, key\)/g, 'const value = (object as any)[key]')
399
+ .replace(/function isJsonPrimitiveWrapper\(object: object\): boolean \{[\s\S]*?return false\s*\}/, 'function isJsonPrimitiveWrapper(_object: object): boolean { return false }')
400
+ .replace('function recur(v: unknown, d = 0): string {', 'let recur: (v: unknown, d?: number) => string\n recur = (v: unknown, d = 0): string => {')
401
+ .replace('function recurUnsafe(v: unknown, d = 0): string {', 'const recurUnsafe = (v: unknown, d = 0): string => {');
402
+ }
403
+ if (norm.endsWith('/effect/src/internal/stream.ts')) {
404
+ return code
405
+ .replace(/const Stream: \{[\s\S]*?this\.channel = channel\s*\} as any\s*Stream\.prototype = \{\s*\[TypeId\]: streamVariance,\s*pipe\(\) \{\s*return pipeArguments\(this, arguments\)\s*\}\s*\}/, `class StreamImpl {\n readonly [TypeId] = streamVariance\n channel: any\n constructor(channel: any) {\n this.channel = channel\n }\n pipe(...args: ReadonlyArray<any>): any {\n return pipeArguments(this, args as any)\n }\n}`)
406
+ .replace(/=> new Stream\(channel\)/, '=> new StreamImpl(channel) as any');
407
+ }
408
+ if (norm.endsWith('/effect/src/internal/effect.ts')) {
409
+ return code.replace(/u\.toString !== Array\.prototype\.toString/g, 'u.toString !== ([] as any).toString');
410
+ }
411
+ if (norm.endsWith('/effect/src/SchemaAST.ts')) {
412
+ const cloneHelper = `function __nsCloneAST<A extends AST>(ast: A, changes: any): A {
413
+ const a: any = ast
414
+ const ann = "annotations" in changes ? changes.annotations : a.annotations
415
+ const chk = "checks" in changes ? changes.checks : a.checks
416
+ const enc = "encoding" in changes ? changes.encoding : a.encoding
417
+ const ctx = "context" in changes ? changes.context : a.context
418
+ let out: any
419
+ switch (a._tag) {
420
+ case "Declaration": out = new Declaration("typeParameters" in changes ? changes.typeParameters : a.typeParameters, "run" in changes ? changes.run : a.run, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks, "encodingRun" in changes ? changes.encodingRun : a.encodingRun); break
421
+ case "Null": out = new Null(ann, chk, enc, ctx); break
422
+ case "Undefined": out = new Undefined(ann, chk, enc, ctx); break
423
+ case "Void": out = new Void(ann, chk, enc, ctx); break
424
+ case "Never": out = new Never(ann, chk, enc, ctx); break
425
+ case "Any": out = new Any(ann, chk, enc, ctx); break
426
+ case "Unknown": out = new Unknown(ann, chk, enc, ctx); break
427
+ case "ObjectKeyword": out = new ObjectKeyword(ann, chk, enc, ctx); break
428
+ case "Enum": out = new Enum("enums" in changes ? changes.enums : a.enums, ann, chk, enc, ctx); break
429
+ case "TemplateLiteral": out = new TemplateLiteral("parts" in changes ? changes.parts : a.parts, ann, chk, enc, ctx); break
430
+ case "UniqueSymbol": out = new UniqueSymbol("symbol" in changes ? changes.symbol : a.symbol, ann, chk, enc, ctx); break
431
+ case "Literal": out = new Literal("literal" in changes ? changes.literal : a.literal, ann, chk, enc, ctx); break
432
+ case "String": out = new String(ann, chk, enc, ctx); break
433
+ case "Number": out = new Number(ann, chk, enc, ctx); break
434
+ case "Boolean": out = new Boolean(ann, chk, enc, ctx); break
435
+ case "Symbol": out = new Symbol(ann, chk, enc, ctx); break
436
+ case "BigInt": out = new BigInt(ann, chk, enc, ctx); break
437
+ case "Arrays": out = new Arrays("isMutable" in changes ? changes.isMutable : a.isMutable, "elements" in changes ? changes.elements : a.elements, "rest" in changes ? changes.rest : a.rest, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks); break
438
+ case "Objects": out = new Objects("propertySignatures" in changes ? changes.propertySignatures : a.propertySignatures, "indexSignatures" in changes ? changes.indexSignatures : a.indexSignatures, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks); break
439
+ case "Suspend": out = new Suspend("thunk" in changes ? changes.thunk : a.thunk, ann, chk, enc, ctx); break
440
+ case "Union": out = new Union("types" in changes ? changes.types : a.types, "options" in changes ? changes.options : a.options, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks); break
441
+ default: out = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, changes); break
442
+ }
443
+ return out as A
444
+ }
445
+ function copy<A extends AST>(ast: A, changes: Partial<AST>): A {`;
446
+ return code
447
+ .replace(/const objectPrototypeKeys = new Set<PropertyKey>\(Reflect\.ownKeys\(Object\.prototype\)\)\.add\("__proto__"\)/, 'const objectPrototypeKeys = new Set<PropertyKey>(["constructor","__defineGetter__","__defineSetter__","hasOwnProperty","__lookupGetter__","__lookupSetter__","isPrototypeOf","propertyIsEnumerable","toString","valueOf","__proto__","toLocaleString"])')
448
+ .replace(/Reflect\.ownKeys\(changes\)/g, '[...Object.getOwnPropertyNames(changes), ...Object.getOwnPropertySymbols(changes)]')
449
+ .replace('function copy<A extends AST>(ast: A, changes: Partial<AST>): A {', cloneHelper)
450
+ .replace('const out = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, changes) as A', 'const out = __nsCloneAST(ast, changes)')
451
+ .replace('const owner = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, { encoding: undefined }) as A', 'const owner = __nsCloneAST(ast, { encoding: undefined })');
452
+ }
453
+ if (norm.endsWith('/effect/src/Schema.ts')) {
454
+ return code.replace(/constructor\(issue: SchemaIssue\.Issue\) \{\s*const stackTraceLimit = getStackTraceLimit\(\)\s*setStackTraceLimit\(0\)\s*try \{\s*super\(\{ issue \}\)\s*\} finally \{\s*setStackTraceLimit\(stackTraceLimit\)\s*\}\s*\}/, `constructor(issue: SchemaIssue.Issue) {\n super({ issue })\n }`);
455
+ }
456
+ if (norm.endsWith('/effect/src/internal/schema/make.ts')) {
457
+ return code.replace(/export function make<S extends Schema\.Constraint>\(ast: S\["ast"\], options\?: object\): S \{[\s\S]*?\n\}/, `export function make<S extends Schema.Constraint>(ast: S["ast"], options?: object): S {
458
+ function Schema() {}
459
+ const self: any = Object.setPrototypeOf(Schema, SchemaProto)
460
+ self[TypeId] = TypeId
461
+ let __make: any = undefined
462
+ let __makeEffect: any = undefined
463
+ let __makeOption: any = undefined
464
+ self.make = (input: any, opts?: any) => (__make ?? (__make = SchemaParser.make(self)))(input, opts)
465
+ self.makeEffect = (input: any, opts?: any) => (__makeEffect ?? (__makeEffect = SchemaParser.makeEffect(self)))(input, opts)
466
+ self.makeOption = (input: any, opts?: any) => (__makeOption ?? (__makeOption = SchemaParser.makeOption(self)))(input, opts)
467
+ self.pipe = (...args: Array<any>) => Pipeable.pipeArguments(self, args)
468
+ self.annotate = (annotations: Schema.Annotations.Annotations) => self.rebuild(SchemaAST.annotate(self.ast, annotations))
469
+ self.annotateKey = (annotations: Schema.Annotations.Key<unknown>) => self.rebuild(SchemaAST.annotateKey(self.ast, annotations))
470
+ self.check = (...checks: readonly [SchemaAST.Check<unknown>, ...Array<SchemaAST.Check<unknown>>]) => self.rebuild(SchemaAST.appendChecks(self.ast, checks))
471
+ self.rebuild = (nextAst: SchemaAST.AST) => make(nextAst, self[RebuildOptions])
472
+ if (
473
+ options &&
474
+ (Object.hasOwn(options, "name") || Object.hasOwn(options, "length") || Object.hasOwn(options, "__proto__"))
475
+ ) {
476
+ for (const __k of [...Object.getOwnPropertyNames(options), ...Object.getOwnPropertySymbols(options)]) {
477
+ const __d = Object.getOwnPropertyDescriptor(options, __k)
478
+ if (__d) Object.defineProperty(self, __k, __d)
479
+ }
480
+ } else {
481
+ Object.assign(self, options)
482
+ }
483
+ self[RebuildOptions] = options
484
+ self.ast = ast
485
+ return self
486
+ }`);
487
+ }
488
+ return code;
489
+ }
490
+ /** Targeted static lowerings for `@effect/ui/src/` modules so unmodified `@effect/ui` compiles natively. */
491
+ function transformEffectUiLib(code, norm) {
492
+ if (norm.endsWith('/@effect/ui/src/html/Html.ts')) {
493
+ return code.replace(/Record<string,\s*VoidElement<any,\s*any,\s*any,\s*any>>/g, 'Record<string, any>');
494
+ }
495
+ if (norm.endsWith('/@effect/ui/src/UiStruct.ts')) {
496
+ return code.replace(/Reflect\.ownKeys\(fields\)/g, '[...Object.getOwnPropertyNames(fields), ...Object.getOwnPropertySymbols(fields)]');
497
+ }
498
+ if (norm.endsWith('/@effect/ui/src/View.ts')) {
499
+ return code
500
+ .replace(/if \(this\.attr !== ElementBuilder\.prototype\.attr\)/, 'if (false)')
501
+ .replace(/let Class = elements === lastElements[\s\S]*?return new Class\(props, elements, running, path \?\? "", store\) as any/, `const __helper = new HelperImpl(props, elements, running, path ?? "", store) as any\n Object.assign(__helper, (elements as any).tags)\n return __helper`)
502
+ .replace(/const copyBuilder = <B extends ElementBuilder<any, any, any, any>>\([\s\S]*?return Object\.assign\(Object\.create\(Object\.getPrototypeOf\(builder\)\), builder\)\n\}/, `const copyBuilder = <B extends ElementBuilder<any, any, any, any>>(\n builder: B\n): B => {\n const __cloned = builder instanceof NoTextBuilder ? new NoTextBuilder(builder.tag, (builder as any).vocabulary) : new (builder.constructor as any)(builder.tag)\n return Object.assign(__cloned, builder)\n}`)
503
+ .replace(/const blank: ElementBuilder<any, any, any, any> = Object\.assign\(\s*Object\.create\(Object\.getPrototypeOf\(builder\)\),\s*blankFields,\s*\{ tag: builder\.tag, removals: \[\] \}\s*\)/, `const blank: ElementBuilder<any, any, any, any> = Object.assign(\n builder instanceof NoTextBuilder ? new NoTextBuilder(builder.tag, (builder as any).vocabulary) : new (builder.constructor as any)(builder.tag),\n blankFields,\n { tag: builder.tag, removals: [] }\n )`)
504
+ .replace(/const root = \(\.\.\.inputs: ReadonlyArray<Input<any, any>>\) =>\s*\(root as any\)\.children\(\.\.\.inputs\)\s*Object\.setPrototypeOf\(root, Object\.getPrototypeOf\(builder\)\)\s*return Object\.assign\(root, builder\) as any/, `const root = (...inputs: ReadonlyArray<Input<any, any>>) =>\n (builder as any).children(...inputs)\n Object.setPrototypeOf(root, builder)\n return Object.assign(root, builder) as any`);
505
+ }
506
+ if (norm.endsWith('/@effect/ui/src/Component.ts')) {
507
+ return code.replace(/return StepProto\.send\.call\(\s*this,\s*target === "self" \? this\["~self"\] as unknown as Headless\.Any : target,\s*message\s*\)/, `const __owner = target === "self" ? this["~self"] as unknown as Headless.Any : target\n return stepWith(this, { sends: [...this.sends, { owner: __owner, message }] })`);
508
+ }
509
+ if (norm.endsWith('/@effect/ui/src/internal/runtime.ts')) {
510
+ return code
511
+ .replace(' let dispatching: Kernel.Instance | undefined\n', '')
512
+ .replace(' let outcome: Dispatched | undefined\n', '')
513
+ .replace(' let hydrating: hydrateRun.Session | undefined\n', '')
514
+ .replace(' let kernelRoot: Kernel.Root | undefined\n', '')
515
+ .replace(' const record: Kernel.Recorder = (inst, draft) => {', ' let dispatching: Kernel.Instance | undefined\n let outcome: Dispatched | undefined\n let hydrating: hydrateRun.Session | undefined\n let kernelRoot: Kernel.Root | undefined\n const record: Kernel.Recorder = (inst, draft) => {');
516
+ }
517
+ if (norm.endsWith('/@effect/ui/src/internal/kernel.ts')) {
518
+ return code
519
+ .replace(/kids = new Array\(views\.length\)\s*for \(let index = 0; index < views\.length; index\+\+\) \{\s*place\(host, node, kids\[index\] = create\(inst, views\[index\]!\), null\)\s*\}/, `kids = []\n for (let index = 0; index < views.length; index++) {\n const __k = create(inst, views[index]!)\n kids.push(__k)\n place(host, node, __k, null)\n }`)
520
+ .replace(/const kids: Array<Rec> = rec\.kids = new Array\(views\.length\)\s*for \(let index = 0; index < views\.length; index\+\+\) \{\s*kids\[index\] = create\(declarer, views\[index\]!\)\s*\}/, `const kids: Array<Rec> = []\n rec.kids = kids\n for (let index = 0; index < views.length; index++) {\n kids.push(create(declarer, views[index]!))\n }`)
521
+ .replace(/const kids: Array<Rec> = new Array\(views\.length\)\s*for \(let index = 0; index < views\.length; index\+\+\) \{\s*place\(host, node, kids\[index\] = create\(inst, views\[index\]!\), null\)\s*\}/, `const kids: Array<Rec> = []\n for (let index = 0; index < views.length; index++) {\n const __k = create(inst, views[index]!)\n kids.push(__k)\n place(host, node, __k, null)\n }`)
522
+ .replace(/let out: Array<Rec> = oldEnd === end \? olds : new Array\(views\.length\)/, `let out: Array<Rec> = oldEnd === end ? olds : Array.from({ length: views.length }) as Array<Rec>`)
523
+ .replace(/out = new Array\(views\.length\)/, `out = Array.from({ length: views.length }) as Array<Rec>`);
524
+ }
525
+ if (norm.endsWith('/@effect/ui/src/Command.ts')) {
526
+ return code
527
+ .replace(/export const Service: <Self>\(\) => \{\s*<const Key extends string>\(\s*key: Key,\s*options\?: undefined\s*\):/, `export const Service: <Self>() => {\n <const Key extends string>(\n key: Key\n ):`)
528
+ .replace(/class CommandService extends Base \{\s*static readonly success = success\s*static readonly error = error\s*static toLayer\(\s*build: \(\(args: any\) => any\) \| Effect\.Effect<\(args: any\) => any, any, any>\s*\): Layer\.Layer<any, any, any> \{\s*return Effect\.isEffect\(build\)\s*\? Layer\.effect\(Base, build\)\s*: Layer\.succeed\(Base, build\)\s*\}\s*\}/, `const CommandService: any = Object.assign(Base, {\n success,\n error,\n toLayer(build: ((args: any) => any) | Effect.Effect<(args: any) => any, any, any>): Layer.Layer<any, any, any> {\n return Effect.isEffect(build) ? Layer.effect(Base, build) : Layer.succeed(Base, build)\n }\n })`);
529
+ }
530
+ if (norm.endsWith('/@effect/ui/src/Query.ts')) {
531
+ let out = code;
532
+ // Replace local `class extends QueryService` in `Service`
533
+ out = out.replace(/return class extends QueryService \{\s*static set\(args: unknown, value: unknown\) \{\s*return write\(QueryService, args, value\)\s*\}\s*\}/, `return Object.assign(QueryService, { set(args: unknown, value: unknown) { return write(QueryService, args, value) } }) as any`);
534
+ // Replace local `class QueryService extends Base` in `queryClass`
535
+ const qsStart = out.indexOf(' class QueryService extends Base {');
536
+ if (qsStart >= 0) {
537
+ const qsEnd = out.indexOf('\n return QueryService', qsStart);
538
+ if (qsEnd > qsStart) {
539
+ const body = out.slice(qsStart + ' class QueryService extends Base {'.length, qsEnd).replace(/\}\s*$/, '');
540
+ const sf = ts.createSourceFile('__q.ts', `class QueryService {${body}}`, ts.ScriptTarget.Latest, true);
541
+ const cls = sf.statements[0];
542
+ const propEntries = [];
543
+ for (const m of cls.members) {
544
+ if (ts.isPropertyDeclaration(m) && m.name) {
545
+ propEntries.push(`${m.name.getText(sf)}: ${m.initializer ? m.initializer.getText(sf) : 'undefined'}`);
546
+ }
547
+ else if (ts.isMethodDeclaration(m) && m.name) {
548
+ const params = m.parameters.map((p) => p.getText(sf)).join(', ');
549
+ const ret = m.type ? `: ${m.type.getText(sf)}` : '';
550
+ propEntries.push(`${m.name.getText(sf)}(${params})${ret} ${m.body.getText(sf)}`);
551
+ }
552
+ }
553
+ const replacement = ` const QueryService: any = Object.assign(Base, {\n ${propEntries.join(',\n ')}\n })`;
554
+ out = out.slice(0, qsStart) + replacement + out.slice(qsEnd);
555
+ }
556
+ }
557
+ // Replace materialize + prototype slot helpers + copyWithout with non-Proxy/non-Reflect equivalents
558
+ const matStart = out.indexOf('const materialize = (');
559
+ const copyBytesEnd = out.indexOf('/**\n * A snapshot of the encoding', matStart);
560
+ if (matStart >= 0 && copyBytesEnd > matStart) {
561
+ const simpleMat = `const materialize = (u: unknown, seen = new Map<object, unknown>()): unknown => {
562
+ if (typeof u === "function") return standIn(u)
563
+ if (typeof u !== "object" || u === null) return u
564
+ if (Equal.symbol in u) return standIn(u)
565
+ const known = seen.get(u)
566
+ if (known !== undefined) return known
567
+ if (u instanceof ArrayBuffer) return u.slice(0)
568
+ if (ArrayBuffer.isView(u)) return new Uint8Array(u.buffer, u.byteOffset, u.byteLength).slice()
569
+ if (Array.isArray(u)) {
570
+ const out: Array<unknown> = []
571
+ seen.set(u, out)
572
+ for (let i = 0; i < u.length; i++) out.push(materialize(u[i], seen))
573
+ return out
574
+ }
575
+ if (u instanceof Date) return new Date(u.getTime())
576
+ if (u instanceof RegExp) return new RegExp(u.source, u.flags)
577
+ if (u instanceof Map) {
578
+ const out = new Map()
579
+ seen.set(u, out)
580
+ u.forEach((value, key) => out.set(materialize(key, seen), materialize(value, seen)))
581
+ return out
582
+ }
583
+ if (u instanceof Set) {
584
+ const out = new Set()
585
+ seen.set(u, out)
586
+ u.forEach((value) => out.add(materialize(value, seen)))
587
+ return out
588
+ }
589
+ const out: Record<PropertyKey, unknown> = Object.create(null)
590
+ seen.set(u, out)
591
+ for (const key of [...Object.getOwnPropertyNames(u), ...Object.getOwnPropertySymbols(u)]) {
592
+ if (key === Hash.symbol) continue
593
+ out[key] = materialize((u as any)[key], seen)
594
+ }
595
+ return out
596
+ }
597
+ const standIns = new WeakMap<object, object>()
598
+ const standIn = (u: object): object => {
599
+ let out = standIns.get(u)
600
+ if (out === undefined) {
601
+ out = Equal.byReferenceUnsafe(Object.create(null) as object)
602
+ standIns.set(u, out)
603
+ }
604
+ return out
605
+ }
606
+ `;
607
+ out = out.slice(0, matStart) + simpleMat + out.slice(copyBytesEnd);
608
+ }
609
+ out = out.replace(/const copyWithout = \(o: object, names: ReadonlyArray<PropertyKey>\): object => \{[\s\S]*?return out\s*\}/, `const copyWithout = (o: object, names: ReadonlyArray<PropertyKey>): object => {
610
+ const drop = new Set<PropertyKey>(names)
611
+ const out: any = Object.create(Object.getPrototypeOf(o))
612
+ for (const key of [...Object.getOwnPropertyNames(o), ...Object.getOwnPropertySymbols(o)]) {
613
+ if (drop.has(key)) continue
614
+ const d = Object.getOwnPropertyDescriptor(o, key)
615
+ if (d) Object.defineProperty(out, key, d)
616
+ }
617
+ if (Object.isFrozen(o)) Object.freeze(out)
618
+ else if (Object.isSealed(o)) Object.seal(out)
619
+ else if (!Object.isExtensible(o)) Object.preventExtensions(out)
620
+ return out
621
+ }`);
622
+ return out;
623
+ }
624
+ return code;
625
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@nstudio/nativescript-compiler-effect-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "9.2.0-alpha.21",
4
+ "description": "The Effect UI adapter of @nstudio/nativescript-compiler: compiles a NativeScript app written with @effect/ui and Effect v4 into a native iOS or Android app with no JavaScript runtime.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "source": "./index.ts",
9
+ "default": "./dist/index.js"
10
+ },
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "dist/"
15
+ ],
16
+ "scripts": {
17
+ "build": "ns-compiled-adapter build .",
18
+ "prepack": "npm run build"
19
+ },
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/nstudio/nativescript-compiler.git",
24
+ "directory": "packages/effect-ui"
25
+ },
26
+ "peerDependencies": {
27
+ "@nstudio/nativescript-compiler": "9.2.0-alpha.21"
28
+ },
29
+ "nativescript": {
30
+ "compilerAdapter": {
31
+ "apiVersion": 1,
32
+ "detect": {
33
+ "priority": 50,
34
+ "dependencies": [
35
+ "@effect/ui",
36
+ "@nstudio/nativescript-effect-ui"
37
+ ],
38
+ "entryImports": [
39
+ "@effect/ui",
40
+ "@nstudio/nativescript-effect-ui"
41
+ ]
42
+ },
43
+ "testedVersions": {
44
+ "@effect/ui": "*",
45
+ "effect": ">=4.0.0 <5.0.0"
46
+ }
47
+ }
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }