svelte-origin 0.0.0 → 1.0.0-next.15

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.
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Core origin factory for svelte-origin
3
+ *
4
+ * This module provides the runtime functions that macros expand to.
5
+ *
6
+ * Key design:
7
+ * - Origins are defined with $origin({...}) using `this` context and real runes
8
+ * - The macro transforms this into __createOrigin with __attrSchema and __create
9
+ * - Components use $attrs.origin(Counter) which expands to $props() + factory call
10
+ */
11
+ import type { OriginFactory, AttrSchema, AttrsFactory, AttachmentFn } from './types';
12
+ export { bindable, isBindable, extractAttrSchema, applyDefaults } from './attrs';
13
+ export type * from './types';
14
+ /**
15
+ * Create an origin factory.
16
+ *
17
+ * This is what the $origin({...}) macro compiles to.
18
+ *
19
+ * The transformation converts the user's object-with-this-context into:
20
+ * - __attrSchema: extracted attr metadata
21
+ * - __create: a function that receives reactive attrs and returns the instance
22
+ *
23
+ * @example
24
+ * // User writes:
25
+ * const Counter = $origin({
26
+ * attrs: $attrs({ count: $bindable(0) }),
27
+ * _internal: $state(0),
28
+ * increment() { this.attrs.count++ }
29
+ * })
30
+ *
31
+ * // Transforms to:
32
+ * const Counter = __createOrigin({
33
+ * __attrSchema: { count: { default: 0, bindable: true, hasDefault: true } },
34
+ * __create: (attrs) => {
35
+ * let _internal = $state(0)
36
+ * return {
37
+ * get attrs() { return attrs },
38
+ * get _internal() { return _internal },
39
+ * set _internal(v) { _internal = v },
40
+ * increment() { attrs.count++ }
41
+ * }
42
+ * }
43
+ * })
44
+ */
45
+ export declare function __createOrigin<TInstance, TAttrs extends Record<string, any>>(config: {
46
+ __attrSchema: AttrSchema;
47
+ __parents?: OriginFactory<any, any>[];
48
+ __create: (attrs: TAttrs, superInstances?: any[]) => TInstance;
49
+ __onInit?: (this: TInstance, ...args: any[]) => void | (() => void);
50
+ __attachments?: Record<string, AttachmentFn>;
51
+ }): OriginFactory<TInstance, TAttrs>;
52
+ /**
53
+ * Helper to get attrs for an origin factory from a raw attrs object.
54
+ * Used when $attrs.origin can't do full static analysis.
55
+ *
56
+ * Creates a writable wrapper around the readonly $props() object.
57
+ * This is necessary because Svelte 5's $props() returns a readonly proxy
58
+ * and the origin's internal __create function needs to write to props.
59
+ *
60
+ * The wrapper:
61
+ * - Reads from the original $props() object (maintaining reactivity)
62
+ * - Writes to a local cache, then syncs back to $props() if the prop is bindable
63
+ * - Falls back to local storage for non-bindable props (internal state)
64
+ *
65
+ * For inherited origins, this ensures parent attrs are recognized.
66
+ *
67
+ * @example
68
+ * // If preprocessor can't resolve the origin's schema statically:
69
+ * let __rawAttrs = $props()
70
+ * let counter = Counter(__attrsFor(Counter, __rawAttrs))
71
+ */
72
+ export declare function __attrsFor<T extends {
73
+ __origin: true;
74
+ }>(factory: T, rawAttrs: Record<string, any>): Record<string, any>;
75
+ /**
76
+ * Get merged attr schema including all parent schemas.
77
+ * Parent schemas are merged first, then child's schema on top (child wins conflicts).
78
+ * Detects circular inheritance to prevent infinite loops.
79
+ */
80
+ export declare function getMergedAttrSchema(factory: OriginFactory<any, any>, visited?: Set<OriginFactory<any, any>>): AttrSchema;
81
+ /**
82
+ * Generate code for $props() destructuring from an attr schema.
83
+ * This is used by the transformer to generate the component's $props() call.
84
+ *
85
+ * @example
86
+ * generateAttrsDestructuring({
87
+ * label: { default: 'Counter', bindable: false, hasDefault: true },
88
+ * count: { default: 0, bindable: true, hasDefault: true }
89
+ * })
90
+ * // Returns: "{ label = 'Counter', count = $bindable(0) }"
91
+ */
92
+ export declare function generateAttrsDestructuring(schema: AttrSchema): string;
93
+ /**
94
+ * Generate code for the reactive attrs object with getters/setters.
95
+ * This links the destructured $props() variables to the attrs object.
96
+ *
97
+ * @example
98
+ * generateReactiveAttrsObject({
99
+ * label: { default: 'Counter', bindable: false, hasDefault: true },
100
+ * count: { default: 0, bindable: true, hasDefault: true }
101
+ * })
102
+ * // Returns: "{ get label() { return label }, get count() { return count }, set count(v) { count = v } }"
103
+ */
104
+ export declare function generateReactiveAttrsObject(schema: AttrSchema): string;
105
+ /**
106
+ * Create a standalone attrs factory.
107
+ *
108
+ * This is what standalone $attrs({...}) compiles to.
109
+ * Allows defining reusable attr schemas that can be imported and extended.
110
+ *
111
+ * @example
112
+ * // User writes:
113
+ * export const BaseAttrs = $attrs({
114
+ * label: 'Default',
115
+ * disabled: false
116
+ * })
117
+ *
118
+ * // Transforms to:
119
+ * export const BaseAttrs = __createAttrs({
120
+ * __attrSchema: { label: {...}, disabled: {...} }
121
+ * })
122
+ *
123
+ * // Extended attrs:
124
+ * export const WidgetAttrs = $attrs([BaseAttrs], { value: $bindable(0) })
125
+ *
126
+ * // Transforms to:
127
+ * export const WidgetAttrs = __createAttrs({
128
+ * __parents: [BaseAttrs],
129
+ * __attrSchema: { value: {...} }
130
+ * })
131
+ */
132
+ export declare function __createAttrs<TAttrs extends Record<string, any>>(config: {
133
+ __attrSchema: AttrSchema;
134
+ __parents?: AttrsFactory<any>[];
135
+ }): AttrsFactory<TAttrs>;
136
+ /**
137
+ * Check if a value is an AttrsFactory
138
+ */
139
+ export declare function isAttrsFactory(value: unknown): value is AttrsFactory<any>;
140
+ /**
141
+ * Get merged attr schema from an AttrsFactory including all parent schemas.
142
+ * Detects circular inheritance to prevent infinite loops.
143
+ */
144
+ export declare function getMergedAttrSchemaFromAttrs(factory: AttrsFactory<any>, visited?: Set<AttrsFactory<any>>): AttrSchema;
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Core types for svelte-origin runtime
3
+ *
4
+ * This file defines the type system for origins.
5
+ *
6
+ * Key concepts:
7
+ * - Origins are defined with $origin({...}) macro using `this` context
8
+ * - The macro transforms to a factory with __attrSchema and __create
9
+ * - __create receives a reactive attrs object and returns an instance
10
+ */
11
+ /**
12
+ * Marker type for bindable attrs.
13
+ * Used inside $origin({ attrs: $attrs({ count: $bindable(0) }) })
14
+ *
15
+ * At macro expansion time, $bindable is replaced with __bindable()
16
+ * to mark attrs that should become $bindable() in the component.
17
+ */
18
+ export interface Bindable<T = unknown> {
19
+ readonly __bindable: true;
20
+ readonly default: T;
21
+ }
22
+ /**
23
+ * Schema describing a single attr's metadata.
24
+ * Extracted at transformation time from the attrs definition.
25
+ */
26
+ export interface AttrSchemaEntry {
27
+ /** The default value (undefined if no default) */
28
+ default: unknown;
29
+ /** Whether this attr is bindable (two-way binding) */
30
+ bindable: boolean;
31
+ /** Whether this attr has a default value */
32
+ hasDefault: boolean;
33
+ }
34
+ /**
35
+ * Full attr schema for an origin.
36
+ * Maps attr name -> schema entry.
37
+ */
38
+ export interface AttrSchema {
39
+ [key: string]: AttrSchemaEntry;
40
+ }
41
+ /**
42
+ * The reactive attrs object passed to the origin factory's __create function.
43
+ * This is created by the component with getters/setters that link to the
44
+ * actual $props() destructured variables.
45
+ *
46
+ * @example
47
+ * // In component after transformation:
48
+ * let { label = 'Counter', count = $bindable(0) } = $props()
49
+ * let __reactiveAttrs = {
50
+ * get label() { return label },
51
+ * get count() { return count },
52
+ * set count(v) { count = v }
53
+ * }
54
+ * let counter = Counter.__create(__reactiveAttrs)
55
+ */
56
+ export type ReactiveAttrs<T> = T extends Record<string, any> ? {
57
+ [K in keyof T]: UnwrapBindable<T[K]>;
58
+ } : Record<string, never>;
59
+ /**
60
+ * Unwrap Bindable<T> to T, pass through other types
61
+ */
62
+ export type UnwrapBindable<T> = T extends Bindable<infer U> ? U : T;
63
+ /**
64
+ * The factory object created by the $origin macro transformation.
65
+ *
66
+ * Contains:
67
+ * - __origin: marker for identification
68
+ * - __attrSchema: metadata about attrs (defaults, bindable markers)
69
+ * - __parents: parent origin factories for inheritance
70
+ * - __create: function that receives reactive attrs and returns instance
71
+ * - __onInit: optional callback that runs after instance creation, can receive extra args
72
+ *
73
+ * The factory is also callable for convenience: `Counter(attrs)` calls `Counter.__create(attrs)`
74
+ * Factory supports: `Counter(attrs?, ...initArgs?)` where initArgs are passed to __onInit
75
+ */
76
+ export interface OriginFactory<TInstance = unknown, TAttrs = Record<string, any>> {
77
+ /** Create an instance with the given reactive attrs and optional init args */
78
+ (attrs?: TAttrs | null, ...initArgs: any[]): TInstance;
79
+ /** Marker to identify origin factories */
80
+ readonly __origin: true;
81
+ /** The attr schema extracted from the definition */
82
+ readonly __attrSchema: AttrSchema;
83
+ /** Parent origin factories (for inheritance) */
84
+ readonly __parents: OriginFactory<any, any>[];
85
+ /** The actual factory function that creates instances */
86
+ readonly __create: (attrs: TAttrs, superInstances?: any[]) => TInstance;
87
+ /** Optional initialization callback that runs after instance creation, receives any extra args passed to factory */
88
+ readonly __onInit?: (this: TInstance, ...args: any[]) => void | (() => void);
89
+ }
90
+ /**
91
+ * Standalone attrs schema factory created by $attrs({...}) outside of $origin.
92
+ * Can be used to define reusable attr schemas.
93
+ *
94
+ * @example
95
+ * // Define reusable attrs
96
+ * export const BaseAttrs = $attrs({
97
+ * label: 'Default',
98
+ * disabled: false
99
+ * })
100
+ *
101
+ * // Extend in origin
102
+ * export const Widget = $origin({
103
+ * props: $attrs([BaseAttrs], {
104
+ * value: $bindable(0)
105
+ * })
106
+ * })
107
+ */
108
+ export interface AttrsFactory<_TAttrs = Record<string, any>> {
109
+ /** Marker to identify attrs factories */
110
+ readonly __attrs: true;
111
+ /** The attr schema */
112
+ readonly __attrSchema: AttrSchema;
113
+ /** Parent attr factories (for inheritance) */
114
+ readonly __parents: AttrsFactory<any>[];
115
+ }
116
+ /**
117
+ * The origin instance has:
118
+ * - attrs: reactive attrs object (passed in)
119
+ * - super: parent instance (if extending)
120
+ * - All other members from the definition (state, getters, methods)
121
+ */
122
+ export interface OriginInstance<TAttrs = Record<string, any>> {
123
+ /** Reactive attrs object */
124
+ readonly attrs: TAttrs;
125
+ /** Parent instance (if extending) */
126
+ readonly super?: any;
127
+ /** Additional members from definition */
128
+ [key: string]: any;
129
+ }
130
+ /**
131
+ * Extract the component attrs type from an origin's attr schema.
132
+ * This is what the component will accept as attrs.
133
+ */
134
+ export type ComponentAttrs<T extends OriginFactory<any, any>> = T extends OriginFactory<any, infer A> ? Partial<A> : Record<string, any>;
135
+ /**
136
+ * Extract the instance type from an origin factory
137
+ */
138
+ export type InstanceOf<T extends OriginFactory<any, any>> = T extends OriginFactory<infer I, any> ? I : never;
139
+ /**
140
+ * Merge parent origins with child definition.
141
+ * The child's attrs are merged with parent attrs.
142
+ * The child gets access to `this.super` for parent methods.
143
+ */
144
+ export type MergedOrigin<Parents extends OriginFactory<any, any>[], TInstance> = TInstance & {
145
+ super: Parents extends [OriginFactory<infer P, any>] ? P : Parents extends [OriginFactory<infer P1, any>, ...infer _Rest] ? P1 : never;
146
+ };
147
+ /**
148
+ * Attrs for a child origin (used with $attrs.for).
149
+ * Extracts the attrs type from the origin's schema.
150
+ */
151
+ export type AttrsFor<T extends OriginFactory<any, any>> = T extends OriginFactory<any, infer A> ? A : Record<string, any>;
152
+ /**
153
+ * Attr mapping for $attrs.for with custom mappings
154
+ */
155
+ export type AttrMapping<TSource = any, TTarget = any> = {
156
+ [K in keyof TTarget]?: (source: TSource) => TTarget[K];
157
+ };
158
+ /**
159
+ * Valid HTML element names for $attrs.for('element').
160
+ * At compile time, this maps to svelte/elements types.
161
+ */
162
+ export type HTMLElementName = keyof HTMLElementTagNameMap | string;
163
+ /**
164
+ * Placeholder type for element attrs.
165
+ * The real type resolution happens at compile time using svelte/elements.
166
+ */
167
+ export type ElementAttrs<_K extends HTMLElementName> = Record<string, any>;
168
+ /**
169
+ * An attachment function that runs when an element is attached.
170
+ * Can return a cleanup function that runs when the element is detached
171
+ * or when the attachment re-runs.
172
+ */
173
+ export type AttachmentFn = (this: any, element: Element) => void | (() => void);
@@ -0,0 +1,24 @@
1
+ /**
2
+ * $attrs.for() transformation logic.
3
+ *
4
+ * This module handles transforming $attrs.for(X) calls which support:
5
+ * - $attrs.for(OriginFactory) - get attrs for an origin factory
6
+ * - $attrs.for('input') - get typed element attrs
7
+ */
8
+ import type MagicString from 'magic-string';
9
+ /**
10
+ * Transform $attrs.for(X) calls.
11
+ * Handles both origin factories ($attrs.for(OriginFactory)) and element names ($attrs.for('input'))
12
+ *
13
+ * If $props() already exists, we extend the existing destructuring with rest syntax.
14
+ * Otherwise, we generate a new $props() call.
15
+ *
16
+ * Supports all TypeScript declaration patterns:
17
+ * - let x = $attrs.for(Factory)
18
+ * - const x = $attrs.for(Factory)
19
+ * - let x: Type = $attrs.for(Factory)
20
+ * - const x: Type<T> = $attrs.for(Factory)
21
+ * - export let x = $attrs.for(Factory)
22
+ * - export const x: Type = $attrs.for('input')
23
+ */
24
+ export declare function transformAttrsForCalls(s: MagicString, source: string, neededImports: Set<string>): boolean;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * $attrs.origin() transformation logic.
3
+ *
4
+ * This module handles transforming $attrs.origin(Factory) calls in component scripts
5
+ * into proper $props() destructuring and factory calls.
6
+ */
7
+ import type MagicString from 'magic-string';
8
+ import { type SchemaResolver } from './schema';
9
+ /**
10
+ * Result from transformAttrsOriginCalls including $$Props info for later injection
11
+ */
12
+ export interface AttrsOriginTransformResult {
13
+ changed: boolean;
14
+ propsTypeDeclaration: string | null;
15
+ }
16
+ /**
17
+ * Transform $attrs.origin(X) calls in component scripts (sync fallback version).
18
+ *
19
+ * This version always uses the fallback approach since no schema resolver is provided.
20
+ * Returns info about $$Props that needs to be injected (but doesn't inject it).
21
+ *
22
+ * Supports all TypeScript declaration patterns:
23
+ * - let x = $attrs.origin(Factory)
24
+ * - const x = $attrs.origin(Factory)
25
+ * - let x: Type = $attrs.origin(Factory)
26
+ * - const x: Type<T> = $attrs.origin(Factory)
27
+ * - export let x = $attrs.origin(Factory)
28
+ * - export const x: Type = $attrs.origin(Factory)
29
+ * - Generic factory call: $attrs.origin(List<T>())
30
+ */
31
+ export declare function transformAttrsOriginCallsSync(s: MagicString, source: string, neededImports: Set<string>): AttrsOriginTransformResult;
32
+ /**
33
+ * Transform $attrs.origin(X) calls in component scripts.
34
+ *
35
+ * When schema is available (via static resolution):
36
+ * ```svelte
37
+ * let counter = $attrs.origin(Counter)
38
+ * ```
39
+ * Becomes:
40
+ * ```svelte
41
+ * let { label = 'Counter', count = $bindable(0), step = 1 } = $props()
42
+ * let counter = Counter({ label, count, step })
43
+ * ```
44
+ *
45
+ * Fallback (when schema isn't statically known):
46
+ * ```svelte
47
+ * let ___attrs: $$Props = $props()
48
+ * let counter = Counter(__attrsFor(Counter, ___attrs))
49
+ * ```
50
+ *
51
+ * Returns info about $$Props that needs to be injected (but doesn't inject it).
52
+ *
53
+ * Supports all TypeScript declaration patterns:
54
+ * - let x = $attrs.origin(Factory)
55
+ * - const x = $attrs.origin(Factory)
56
+ * - let x: Type = $attrs.origin(Factory)
57
+ * - const x: Type<T> = $attrs.origin(Factory)
58
+ * - export let x = $attrs.origin(Factory)
59
+ * - export const x: Type = $attrs.origin(Factory)
60
+ * - Generic factory call: $attrs.origin(List<T>())
61
+ */
62
+ export declare function transformAttrsOriginCalls(s: MagicString, source: string, neededImports: Set<string>, schemaResolver?: SchemaResolver): Promise<AttrsOriginTransformResult>;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Attribute schema parsing and generation utilities.
3
+ *
4
+ * This module handles parsing $attrs({...}) content and generating
5
+ * the __attrSchema object that describes each attribute's metadata.
6
+ */
7
+ /**
8
+ * Parsed attribute details for code generation
9
+ */
10
+ export interface AttrDetail {
11
+ key: string;
12
+ defaultValue: string;
13
+ bindable: boolean;
14
+ hasDefault: boolean;
15
+ }
16
+ /**
17
+ * Generate __attrSchema code from the attrs source.
18
+ *
19
+ * Input: 'label: "Counter", count: $bindable(0), step: undefined as undefined | number'
20
+ * Output: '{ label: { default: "Counter", bindable: false, hasDefault: true }, ... }'
21
+ */
22
+ export declare function generateAttrSchemaFromSource(attrsSource: string): string;
23
+ /**
24
+ * Parse attrs source and return structured details for each attr.
25
+ *
26
+ * Input: 'label: "Counter", count: $bindable(0), step: 1 as number'
27
+ * Output: [{ key: 'label', defaultValue: '"Counter"', bindable: false, hasDefault: true }, ...]
28
+ */
29
+ export declare function parseAttrsSource(attrsSource: string): AttrDetail[];
30
+ /**
31
+ * Split attrs source by top-level commas.
32
+ * Handles strings and comments correctly.
33
+ */
34
+ export declare function splitAttrsSource(source: string): string[];
35
+ /**
36
+ * Parse members from an object literal source.
37
+ * This is a simplified parser - a proper implementation would use AST.
38
+ */
39
+ export interface ObjectMember {
40
+ key: string;
41
+ value: string;
42
+ isGetter: boolean;
43
+ isSetter: boolean;
44
+ isMethod: boolean;
45
+ isAsync: boolean;
46
+ isGenerator: boolean;
47
+ isComputed: boolean;
48
+ }
49
+ /**
50
+ * Parse members from an object literal source.
51
+ */
52
+ export declare function parseObjectMembers(source: string): ObjectMember[];
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Code generation utilities for svelte-origin transformations
3
+ */
4
+ /**
5
+ * Generate the import statement for runtime functions.
6
+ *
7
+ * @example
8
+ * generateRuntimeImport(['__createOrigin', '__attrsFor'])
9
+ * // Returns: "import { __createOrigin, __attrsFor } from 'svelte-origin/runtime'"
10
+ */
11
+ export declare function generateRuntimeImport(functions: string[]): string;
12
+ /**
13
+ * Indent each line of code by a given amount
14
+ */
15
+ export declare function indent(code: string, tabs?: number): string;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Core transformation logic for svelte-origin
3
+ *
4
+ * This module is the main entry point for transformations that convert
5
+ * macro syntax into runtime calls.
6
+ *
7
+ * Key transformations:
8
+ * 1. $origin({...}) in .svelte.ts files -> __createOrigin({...})
9
+ * 2. $attrs.origin(Counter) in .svelte files -> $props() + factory call
10
+ * 3. $attrs.for(Child) -> attr forwarding for origin factories
11
+ * 4. $attrs.for('input') -> typed element attrs
12
+ *
13
+ * The actual transformation logic is split into focused modules:
14
+ * - declaration-parser.ts: TypeScript declaration parsing utilities
15
+ * - attrs-schema.ts: $attrs schema generation and parsing
16
+ * - origin-transform.ts: $origin() transformation
17
+ * - standalone-attrs-transform.ts: standalone $attrs() transformation
18
+ * - attrs-origin-transform.ts: $attrs.origin() transformation
19
+ * - attrs-for-transform.ts: $attrs.for() transformation
20
+ */
21
+ import MagicString from 'magic-string';
22
+ import type { SchemaResolver } from './schema';
23
+ export type { SchemaResolver } from './schema';
24
+ export type { AttrDetail } from './attrs-schema';
25
+ export type { AttrsOriginTransformResult } from './attrs-origin-transform';
26
+ export interface TransformOptions {
27
+ /** The filename being transformed */
28
+ filename?: string;
29
+ /** Whether this is a component script (vs a module) */
30
+ isComponent?: boolean;
31
+ /** Schema resolver for static analysis of $attrs.origin() calls */
32
+ schemaResolver?: SchemaResolver;
33
+ }
34
+ export interface TransformResult {
35
+ /** The transformed code */
36
+ code: string;
37
+ /** Whether any transformations were made */
38
+ changed: boolean;
39
+ /** Source map (if changes were made) */
40
+ map?: ReturnType<MagicString['generateMap']>;
41
+ }
42
+ /**
43
+ * Transform a script/module containing svelte-origin macros.
44
+ * Main entry point for transformations.
45
+ *
46
+ * @overload Sync version when no schemaResolver is provided
47
+ * @overload Async version when schemaResolver is provided
48
+ */
49
+ export declare function transformScript(source: string, options?: TransformOptions & {
50
+ schemaResolver?: undefined;
51
+ }): TransformResult;
52
+ export declare function transformScript(source: string, options: TransformOptions & {
53
+ schemaResolver: SchemaResolver;
54
+ }): Promise<TransformResult>;
55
+ /**
56
+ * Transform script content from the script hook.
57
+ *
58
+ * This is similar to transformScriptAsync but designed for the script hook
59
+ * where the content is already extracted (no <script> tags).
60
+ * Imports are always prepended at the start of the content.
61
+ */
62
+ export declare function transformScriptContent(source: string, options: TransformOptions): Promise<TransformResult>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * TypeScript/JavaScript declaration parsing utilities.
3
+ *
4
+ * This module handles parsing variable declarations from source code,
5
+ * with full support for TypeScript type annotations, generics, and exports.
6
+ */
7
+ /**
8
+ * Information about a variable declaration found in source code.
9
+ * Handles all TypeScript declaration variants:
10
+ *
11
+ * Basic:
12
+ * let x = value
13
+ * const x = value
14
+ *
15
+ * With type annotation:
16
+ * let x: Type = value
17
+ * const x: Type<T> = value
18
+ * const x: Type<T, U<V>> = value
19
+ *
20
+ * With export:
21
+ * export let x = value
22
+ * export const x: Type = value
23
+ *
24
+ * Complex types:
25
+ * let x: Type | Other = value
26
+ * let x: Type & Other = value
27
+ * let x: () => Type = value
28
+ */
29
+ export interface VariableDeclaration {
30
+ /** The variable name */
31
+ varName: string;
32
+ /** Start index of the entire declaration (including export/let/const) */
33
+ startIndex: number;
34
+ /** Index where the value expression starts (after =) */
35
+ valueStartIndex: number;
36
+ /** Whether it has 'export' keyword */
37
+ hasExport: boolean;
38
+ /** The type annotation if present (without the colon) */
39
+ typeAnnotation: string | null;
40
+ }
41
+ /**
42
+ * Find all variable declarations that are assigned a specific macro call.
43
+ * Handles all TypeScript declaration patterns:
44
+ *
45
+ * - let x = $macro(...)
46
+ * - const x = $macro(...)
47
+ * - let x: Type = $macro(...)
48
+ * - const x: Type<T> = $macro(...)
49
+ * - export let x = $macro(...)
50
+ * - export const x: Type = $macro(...)
51
+ *
52
+ * @param source The source code to search
53
+ * @param macroPattern The macro to find (e.g., '$attrs.origin', '$attrs.for', '$origin')
54
+ * @returns Array of declarations with their metadata
55
+ */
56
+ export declare function findVariableDeclarationsWithMacro(source: string, macroPattern: string): (VariableDeclaration & {
57
+ macroOpenParen: number;
58
+ })[];
59
+ /**
60
+ * Look backwards from a position to find a variable declaration.
61
+ * Handles: [export] (let|const) varName [: Type] =
62
+ */
63
+ export declare function findDeclarationBefore(source: string, beforeIndex: number): VariableDeclaration | null;
64
+ /**
65
+ * Check if the source already has a $$Props type declaration.
66
+ * Looks for 'type $$Props' or 'interface $$Props' patterns.
67
+ */
68
+ export declare function hasExistingPropsDeclaration(source: string): boolean;
69
+ /**
70
+ * Find the position right after imports to inject $$Props.
71
+ * Returns the position after the last import statement, or after the script tag.
72
+ *
73
+ * Handles both single-line and multi-line imports:
74
+ * - import { x } from 'y'
75
+ * - import {\n x,\n y\n} from 'z'
76
+ */
77
+ export declare function findPropsInjectionPosition(source: string): number;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Get the svelte/elements type import for an HTML element name.
3
+ *
4
+ * Uses svelteHTML.IntrinsicElements for type-checking compatibility with Svelte's
5
+ * internal createElement function, which expects IntrinsicElements types.
6
+ *
7
+ * @param element - The HTML element name (e.g., 'input', 'button', 'div')
8
+ * @returns The full type expression using svelteHTML.IntrinsicElements
9
+ */
10
+ export declare function getElementTypeImport(element: string): string;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * $origin() transformation logic.
3
+ *
4
+ * This module handles transforming $origin({...}) macro calls into
5
+ * __createOrigin({...}) runtime calls with proper code generation.
6
+ */
7
+ import type MagicString from 'magic-string';
8
+ /**
9
+ * Result of transforming the origin body
10
+ */
11
+ export interface TransformOriginBodyResult {
12
+ body: string;
13
+ attachments: string[];
14
+ }
15
+ /**
16
+ * Transform $origin({...}) macro calls.
17
+ *
18
+ * Input:
19
+ * ```ts
20
+ * export const Counter = $origin({
21
+ * attrs: $attrs({
22
+ * label: 'Counter',
23
+ * count: $bindable(0)
24
+ * }),
25
+ * _internal: $state(0),
26
+ * get double() { return $derived(this.attrs.count * 2) },
27
+ * increment() { this.attrs.count++ }
28
+ * })
29
+ * ```
30
+ *
31
+ * Output:
32
+ * ```ts
33
+ * export const Counter = __createOrigin({
34
+ * __attrSchema: {
35
+ * label: { default: "Counter", bindable: false, hasDefault: true },
36
+ * count: { default: 0, bindable: true, hasDefault: true }
37
+ * },
38
+ * __create: (attrs) => {
39
+ * let _internal = $state(0)
40
+ * return {
41
+ * get attrs() { return attrs },
42
+ * get _internal() { return _internal },
43
+ * set _internal(v) { _internal = v },
44
+ * get double() { return $derived(attrs.count * 2) },
45
+ * increment() { attrs.count++ }
46
+ * }
47
+ * }
48
+ * })
49
+ * ```
50
+ */
51
+ export declare function transformOriginCalls(s: MagicString, source: string, neededImports: Set<string>): boolean;