create-nativue 0.14.0 → 0.15.3

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/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # create-nativue
2
2
 
3
- Creates a [nativue](https://github.com/nativue/nativue) app, with its iOS and Android projects:
3
+ Creates a [nativue](https://github.com/nativue/nativue) app, with its iOS and Android projects, or
4
+ a package with native code (below):
4
5
 
5
6
  ```sh
6
7
  npm create nativue@latest my-app
@@ -23,4 +24,13 @@ The new app has a starter screen, TypeScript, and these scripts:
23
24
  | `npm run build` | bundles the app for a release build |
24
25
  | `npm run typecheck` | type-checks the app, templates included |
25
26
 
27
+ ## A package with native code
28
+
29
+ ```sh
30
+ npm create nativue@latest nativue-battery -- --module
31
+ ```
32
+
33
+ creates a package whose JavaScript calls a function in Swift and Kotlin, ready to install in an app
34
+ and grow from there: [writing a package with native code](https://github.com/nativue/nativue/blob/main/docs/packages.md#writing-a-package-with-native-code).
35
+
26
36
  Next: [Getting started](https://github.com/nativue/nativue/blob/main/docs/getting-started.md).
package/index.mjs CHANGED
@@ -1,24 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  // npm create nativue@latest my-app [-- --bundle-id com.company.myapp]
3
- // Copies template/ into a new folder and fills in the app's names.
4
- import { cpSync, existsSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
5
- import { basename, join, relative, resolve } from 'node:path'
3
+ // npm create nativue@latest nativue-battery -- --module
4
+ // Copies template/app (an app) or template/package (a package with native code) into a new folder
5
+ // and fills in the names.
6
+ import {
7
+ cpSync,
8
+ existsSync,
9
+ mkdirSync,
10
+ readdirSync,
11
+ readFileSync,
12
+ renameSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from 'node:fs'
16
+ import { basename, dirname, join, relative, resolve } from 'node:path'
6
17
  import { createInterface } from 'node:readline/promises'
7
18
  import { fileURLToPath } from 'node:url'
8
19
  import { parseArgs } from 'node:util'
9
20
 
10
- const TEMPLATE_DIRECTORY = fileURLToPath(new URL('./template', import.meta.url))
11
- const TEXT_FILE = /(\.(json|vue|ts|md)|gitignore)$/
21
+ const APP_TEMPLATE = fileURLToPath(new URL('./template/app', import.meta.url))
22
+ const PACKAGE_TEMPLATE = fileURLToPath(new URL('./template/package', import.meta.url))
23
+ const TEXT_FILE = /(\.(json|vue|ts|md|swift|kt|kts)|gitignore)$/
24
+ // npm's rule: lowercase, an optional @scope.
25
+ const PACKAGE_NAME = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/
12
26
  // Also the Android package and applicationId, which can't have hyphens.
13
27
  const BUNDLE_ID = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$/
14
28
  const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
15
29
 
16
- async function askProjectName() {
30
+ async function askName(question, fallback) {
17
31
  const prompt = createInterface({ input: process.stdin, output: process.stdout })
18
- const answer = await prompt.question('Project name: (my-app) ')
32
+ const answer = await prompt.question(`${question}: (${fallback}) `)
19
33
  prompt.close()
20
34
 
21
- return answer.trim() || 'my-app'
35
+ return answer.trim() || fallback
22
36
  }
23
37
 
24
38
  // "My.Cool_App" -> "my-cool_app"
@@ -48,52 +62,157 @@ function fail(message) {
48
62
  process.exit(1)
49
63
  }
50
64
 
65
+ function filled(text, values) {
66
+ return Object.entries(values).reduce(
67
+ (result, [placeholder, value]) => result.replaceAll(placeholder, value),
68
+ text,
69
+ )
70
+ }
71
+
72
+ /** In the files' text, and in their paths: template/package has __PASCAL__Plugin.swift. */
51
73
  function fillPlaceholders(directory, values) {
52
- for (const file of filesIn(directory).filter((path) => TEXT_FILE.test(path))) {
53
- const source = readFileSync(file, 'utf8')
54
- const filled = Object.entries(values).reduce(
55
- (text, [placeholder, value]) => text.replaceAll(placeholder, value),
56
- source,
57
- )
58
- if (filled !== source) writeFileSync(file, filled)
74
+ for (const file of filesIn(directory)) {
75
+ if (TEXT_FILE.test(file)) {
76
+ const source = readFileSync(file, 'utf8')
77
+ const text = filled(source, values)
78
+
79
+ if (text !== source) writeFileSync(file, text)
80
+ }
81
+
82
+ const path = filled(relative(directory, file), values)
83
+
84
+ if (path === relative(directory, file)) continue
85
+
86
+ mkdirSync(dirname(join(directory, path)), { recursive: true })
87
+ renameSync(file, join(directory, path))
88
+ }
89
+ removeEmptyFolders(directory)
90
+ }
91
+
92
+ function removeEmptyFolders(directory) {
93
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
94
+ if (!entry.isDirectory()) continue
95
+
96
+ const path = join(directory, entry.name)
97
+
98
+ removeEmptyFolders(path)
99
+ if (readdirSync(path).length === 0) rmSync(path, { recursive: true })
100
+ }
101
+ }
102
+
103
+ /** Copies a template into a new folder, which may exist only if empty. */
104
+ function copyTemplate(template, directory) {
105
+ if (existsSync(directory) && readdirSync(directory).length > 0) {
106
+ fail(`${directory} already exists and isn't empty.`)
59
107
  }
108
+
109
+ cpSync(template, directory, { recursive: true })
110
+ // npm drops .gitignore files from published packages, so the templates ship it without the dot.
111
+ renameSync(join(directory, 'gitignore'), join(directory, '.gitignore'))
112
+ }
113
+
114
+ // aapt2 and Kotlin refuse them as package names.
115
+ const KOTLIN_KEYWORDS = new Set(
116
+ `abstract as assert boolean break byte case catch char class const continue default do double else
117
+ enum extends false final finally float for fun goto if implements import in instanceof int interface
118
+ is long native new null object package private protected public return short static strictfp super
119
+ switch synchronized this throw throws transient true try typealias typeof val var void volatile when
120
+ while`.split(/\s+/),
121
+ )
122
+
123
+ /**
124
+ * From the whole name, like the linker's Swift module, so two packages never share a class:
125
+ * "@acme/battery-level" -> AcmeBatteryLevelPlugin, acmeBatteryLevel.hello, acme.batterylevel.
126
+ */
127
+ function moduleNames(packageName) {
128
+ const words = packageName.split(/[^a-zA-Z0-9]+/).filter(Boolean)
129
+ const joined = words.map((word) => word[0].toUpperCase() + word.slice(1)).join('')
130
+ // Swift and Kotlin names start with a letter.
131
+ const pascal = /^\d/.test(joined) ? `Module${joined}` : joined
132
+ const scope = packageName.startsWith('@') ? words[0] : 'nativue'
133
+ const name = packageName.startsWith('@') ? words.slice(1) : words
134
+ const kotlinPackage = [scope, name.join('')]
135
+ .map((part) => part.toLowerCase())
136
+ .map((part) => (/^\d/.test(part) || KOTLIN_KEYWORDS.has(part) ? `module${part}` : part))
137
+ .join('.')
138
+
139
+ return { pascal, camel: pascal[0].toLowerCase() + pascal.slice(1), kotlinPackage }
140
+ }
141
+
142
+ function createPackage(packageName) {
143
+ if (!PACKAGE_NAME.test(packageName))
144
+ fail(`"${packageName}" isn't a valid npm package name, e.g. nativue-battery`)
145
+
146
+ const directory = resolve(basename(packageName))
147
+ const path = relative(process.cwd(), directory) || '.'
148
+ const { pascal, camel, kotlinPackage } = moduleNames(packageName)
149
+
150
+ if (!pascal) fail('The package name needs at least one letter or digit.')
151
+ // nativue's own: its Swift module, Gradle project and NativuePlugin protocol.
152
+ if (pascal === 'Nativue')
153
+ fail(`"${packageName}" is nativue's own name: add a word, e.g. nativue-battery`)
154
+
155
+ copyTemplate(PACKAGE_TEMPLATE, directory)
156
+ fillPlaceholders(directory, {
157
+ __PACKAGE_NAME__: packageName,
158
+ __NAME__: basename(packageName),
159
+ __PASCAL__: pascal,
160
+ __MODULE__: camel,
161
+ __KOTLIN_PACKAGE__: kotlinPackage,
162
+ __KOTLIN_PATH__: kotlinPackage.replaceAll('.', '/'),
163
+ __NATIVUE_VERSION__: version,
164
+ })
165
+
166
+ console.log(`
167
+ Created ${packageName} in ${path}
168
+
169
+ cd ${path}
170
+ npm install
171
+
172
+ Try it in an app: npm install ${directory} from the app, then npm run ios or npm run android
173
+ Its native side: ios/${pascal}Plugin.swift and android/src/main/java/${kotlinPackage.replaceAll('.', '/')}/${pascal}Plugin.kt
174
+ `)
60
175
  }
61
176
 
62
177
  const { values: options, positionals } = parseArgs({
63
178
  allowPositionals: true,
64
- options: { 'bundle-id': { type: 'string' } },
179
+ options: { 'bundle-id': { type: 'string' }, module: { type: 'boolean' } },
65
180
  })
66
181
 
67
- const projectName = positionals[0] ?? (await askProjectName())
68
- if (/\s/.test(projectName)) {
69
- fail(`"${projectName}" has spaces: use dashes or underscores instead, e.g. my-app or my_app`)
182
+ if (options.module && options['bundle-id']) {
183
+ fail('--bundle-id is for an app; a package gets its names from the package name.')
70
184
  }
71
185
 
72
- const projectDirectory = resolve(projectName)
73
- const projectPath = relative(process.cwd(), projectDirectory) || '.'
74
- const slug = slugify(basename(projectDirectory))
75
- // Bundle ids and URL schemes allow neither dashes nor underscores here, and start with a letter.
76
- const urlScheme = slug.replace(/[-_]/g, '').replace(/^(?=\d)/, 'app')
77
- const bundleId = options['bundle-id'] ?? `com.example.${urlScheme}`
78
-
79
- if (!slug) fail('The project name needs at least one letter or digit.')
80
- if (!BUNDLE_ID.test(bundleId)) fail(`"${bundleId}" is not a valid bundle id, e.g. com.company.app`)
81
- if (existsSync(projectDirectory) && readdirSync(projectDirectory).length > 0) {
82
- fail(`${projectDirectory} already exists and isn't empty.`)
83
- }
186
+ if (options.module)
187
+ createPackage(positionals[0] ?? (await askName('Package name', 'nativue-my-module')))
188
+ else await createApp(positionals[0] ?? (await askName('Project name', 'my-app')))
84
189
 
85
- cpSync(TEMPLATE_DIRECTORY, projectDirectory, { recursive: true })
86
- // npm drops .gitignore files from published packages, so the template ships it without the dot.
87
- renameSync(join(projectDirectory, 'gitignore'), join(projectDirectory, '.gitignore'))
88
- fillPlaceholders(projectDirectory, {
89
- __PACKAGE_NAME__: slug,
90
- __DISPLAY_NAME__: displayNameOf(slug),
91
- __BUNDLE_ID__: bundleId,
92
- __URL_SCHEME__: urlScheme,
93
- __NATIVUE_VERSION__: `^${version}`,
94
- })
190
+ async function createApp(projectName) {
191
+ if (/\s/.test(projectName)) {
192
+ fail(`"${projectName}" has spaces: use dashes or underscores instead, e.g. my-app or my_app`)
193
+ }
95
194
 
96
- console.log(`
195
+ const projectDirectory = resolve(projectName)
196
+ const projectPath = relative(process.cwd(), projectDirectory) || '.'
197
+ const slug = slugify(basename(projectDirectory))
198
+ // Bundle ids and URL schemes allow neither dashes nor underscores here, and start with a letter.
199
+ const urlScheme = slug.replace(/[-_]/g, '').replace(/^(?=\d)/, 'app')
200
+ const bundleId = options['bundle-id'] ?? `com.example.${urlScheme}`
201
+
202
+ if (!slug) fail('The project name needs at least one letter or digit.')
203
+ if (!BUNDLE_ID.test(bundleId))
204
+ fail(`"${bundleId}" is not a valid bundle id, e.g. com.company.app`)
205
+
206
+ copyTemplate(APP_TEMPLATE, projectDirectory)
207
+ fillPlaceholders(projectDirectory, {
208
+ __PACKAGE_NAME__: slug,
209
+ __DISPLAY_NAME__: displayNameOf(slug),
210
+ __BUNDLE_ID__: bundleId,
211
+ __URL_SCHEME__: urlScheme,
212
+ __NATIVUE_VERSION__: `^${version}`,
213
+ })
214
+
215
+ console.log(`
97
216
  Created ${displayNameOf(slug)} in ${projectPath}
98
217
 
99
218
  cd ${projectPath}
@@ -106,3 +225,4 @@ Created ${displayNameOf(slug)} in ${projectPath}
106
225
 
107
226
  Bundle id: ${bundleId} (set it with --bundle-id, or later in nativue.config.ts)
108
227
  `)
228
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "create-nativue",
3
- "version": "0.14.0",
4
- "description": "Creates a Nativue app: npm create nativue@latest my-app",
3
+ "version": "0.15.3",
4
+ "description": "Creates a nativue app, or a package with native code: npm create nativue@latest my-app",
5
5
  "keywords": [
6
6
  "vue",
7
7
  "native",
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "devDependencies": {
17
17
  "prettier": "^3.10.1",
18
- "typescript": "^5.9.3",
18
+ "typescript": "^6.0.3",
19
19
  "vue-tsc": "^3.3.14"
20
20
  }
21
21
  }
@@ -0,0 +1,6 @@
1
+ {
2
+ "semi": false,
3
+ "singleQuote": true,
4
+ "printWidth": 100,
5
+ "htmlWhitespaceSensitivity": "ignore"
6
+ }
@@ -0,0 +1,27 @@
1
+ # __PACKAGE_NAME__
2
+
3
+ A [nativue](https://github.com/nativue/nativue) package with native code.
4
+
5
+ ```sh
6
+ npm install __PACKAGE_NAME__
7
+ ```
8
+
9
+ Then rebuild the app (`npm run ios`, `npm run android`): its native code is linked when the app is
10
+ built.
11
+
12
+ ```ts
13
+ import { hello } from '__PACKAGE_NAME__'
14
+
15
+ hello('nativue') // 'Hello, nativue, from iOS'
16
+ ```
17
+
18
+ ## Developing it
19
+
20
+ - `src/index.ts` is what apps import; `ios/__PASCAL__Plugin.swift` and
21
+ `android/src/main/java/__KOTLIN_PATH__/__PASCAL__Plugin.kt` are its native side.
22
+ - Try it in an app with `npm install ../__NAME__` from the app, then rebuild the app.
23
+ - `npm run format` formats it with nativue's Prettier settings (`.prettierrc.json`).
24
+ - Swift packages it needs go in `package.json`'s `"nativue": { "ios": { "dependencies": [...] } }`,
25
+ Android libraries in `android/build.gradle.kts`.
26
+ - To change the app's `Info.plist`, manifest or Gradle files, add a config plugin:
27
+ [packages.md](https://github.com/nativue/nativue/blob/main/docs/packages.md#changing-the-apps-native-files).
@@ -0,0 +1,22 @@
1
+ // The Android side of __PACKAGE_NAME__, added to the app by nativue.settings.gradle.kts.
2
+ plugins {
3
+ id("com.android.library")
4
+ }
5
+
6
+ android {
7
+ namespace = "__KOTLIN_PACKAGE__"
8
+ compileSdk = 37
9
+
10
+ defaultConfig {
11
+ minSdk = 24
12
+ }
13
+
14
+ compileOptions {
15
+ sourceCompatibility = JavaVersion.VERSION_17
16
+ targetCompatibility = JavaVersion.VERSION_17
17
+ }
18
+ }
19
+
20
+ dependencies {
21
+ implementation(project(":nativue"))
22
+ }
@@ -0,0 +1,13 @@
1
+ package __KOTLIN_PACKAGE__
2
+
3
+ import dev.nativue.NativuePlugin
4
+ import dev.nativue.PluginRegistry
5
+
6
+ /** __MODULE__.* in src/index.ts. Apps rebuild after installing or updating it. */
7
+ class __PASCAL__Plugin : NativuePlugin {
8
+ override fun register(registry: PluginRegistry) {
9
+ registry.addFunction("__MODULE__.hello") { arguments ->
10
+ "Hello, ${arguments.firstOrNull() ?: "world"}, from Android"
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,2 @@
1
+ node_modules
2
+ android/build
@@ -0,0 +1,12 @@
1
+ import Nativue
2
+
3
+ /// __MODULE__.* in src/index.ts. Apps rebuild after installing or updating it.
4
+ public final class __PASCAL__Plugin: NativuePlugin {
5
+ public init() {}
6
+
7
+ public func register(in registry: PluginRegistry) {
8
+ registry.addFunction("__MODULE__.hello") { arguments in
9
+ "Hello, \(arguments.first as? String ?? "world"), from iOS"
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "__PACKAGE_NAME__",
3
+ "version": "0.1.0",
4
+ "description": "",
5
+ "keywords": [
6
+ "vue",
7
+ "native",
8
+ "nativue"
9
+ ],
10
+ "type": "module",
11
+ "exports": {
12
+ ".": "./src/index.ts"
13
+ },
14
+ "scripts": {
15
+ "typecheck": "vue-tsc",
16
+ "format": "prettier --write src"
17
+ },
18
+ "peerDependencies": {
19
+ "@nativue/core": ">=__NATIVUE_VERSION__"
20
+ },
21
+ "devDependencies": {
22
+ "@nativue/core": "^__NATIVUE_VERSION__",
23
+ "prettier": "^3.10.1",
24
+ "typescript": "^6.0.3",
25
+ "vue-tsc": "^3.3.14"
26
+ },
27
+ "nativue": {
28
+ "ios": {
29
+ "sources": "ios",
30
+ "plugin": "__PASCAL__Plugin"
31
+ },
32
+ "android": {
33
+ "sources": "android",
34
+ "plugin": "__KOTLIN_PACKAGE__.__PASCAL__Plugin"
35
+ }
36
+ },
37
+ "files": [
38
+ "src",
39
+ "ios",
40
+ "android/build.gradle.kts",
41
+ "android/src"
42
+ ]
43
+ }
@@ -0,0 +1,4 @@
1
+ import { requireNativeFunction } from '@nativue/core'
2
+
3
+ // ios/ and android/: addFunction returns right away; addAsyncFunction returns a Promise.
4
+ export const hello = requireNativeFunction<(name: string) => string>('__MODULE__.hello')
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "@nativue/core/tsconfig.base.json",
3
+ "include": ["src"]
4
+ }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes