createModule implements the core module creation logic This function handles the QuickJS module creation and registration: 1. Module creation phase: create C module and declare exports 2. Module initialization phase: set actual export values via proxy The module will be available for import in JavaS
(ctx *Context, builder *ModuleBuilder)
| 124 | // 2. Module initialization phase: set actual export values via proxy |
| 125 | // The module will be available for import in JavaScript code |
| 126 | func createModule(ctx *Context, builder *ModuleBuilder) error { |
| 127 | // Step 1: Validate module builder |
| 128 | if err := validateModuleBuilder(builder); err != nil { |
| 129 | return fmt.Errorf("module validation failed: %v", err) |
| 130 | } |
| 131 | snapshot := cloneModuleBuilder(builder) |
| 132 | |
| 133 | // Step 2: Store a build snapshot in HandleStore for initialization access. |
| 134 | builderID := ctx.handleStore.Store(snapshot) |
| 135 | |
| 136 | // Step 3: Prepare export names for C function |
| 137 | exportNames := make([]*C.char, len(snapshot.exports)) |
| 138 | exportCount := len(snapshot.exports) |
| 139 | |
| 140 | // Convert Go strings to C strings |
| 141 | for i, export := range snapshot.exports { |
| 142 | exportNames[i] = C.CString(export.Name) |
| 143 | } |
| 144 | |
| 145 | // Prepare parameters for C function call |
| 146 | moduleName := C.CString(snapshot.name) |
| 147 | var exportNamesPtr **C.char |
| 148 | if exportCount > 0 { |
| 149 | exportNamesPtr = &exportNames[0] |
| 150 | } |
| 151 | |
| 152 | // Step 4: Call C function to create module |
| 153 | result := C.CreateModule( |
| 154 | ctx.ref, |
| 155 | moduleName, |
| 156 | exportNamesPtr, |
| 157 | C.int(exportCount), |
| 158 | C.int32_t(builderID), |
| 159 | ) |
| 160 | |
| 161 | // Step 5: Clean up C strings |
| 162 | C.free(unsafe.Pointer(moduleName)) |
| 163 | for _, cStr := range exportNames { |
| 164 | C.free(unsafe.Pointer(cStr)) |
| 165 | } |
| 166 | |
| 167 | // Step 6: Check result and handle errors |
| 168 | if result < 0 { |
| 169 | // Clean up HandleStore on failure |
| 170 | ctx.handleStore.Delete(builderID) |
| 171 | return ctx.Exception() |
| 172 | } |
| 173 | |
| 174 | // Module is now created and registered, ready for import |
| 175 | return nil |
| 176 | } |
no test coverage detected