@octane-xplat/bamboo 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,4 +37,19 @@ const webPlugins = xplatBamboo()
37
37
  const nativePlugins = xplatBamboo({ native: true })
38
38
  ```
39
39
 
40
+ Platform conditions use the same build-time compiler as ordinary CSS. Add
41
+ `xplatCss('web')` from `@octane-xplat/cli/vite` to web plugins; native presets
42
+ include it. Keep the portable utility subset unless you explicitly extend it.
43
+ SSR generation with platform conditions is currently unsupported.
44
+
45
+ ```ts
46
+ import { css } from './styled-system/css'
47
+
48
+ const card = css({
49
+ padding: '4',
50
+ _web: { color: 'primary' },
51
+ _mobile: { color: 'text' },
52
+ })
53
+ ```
54
+
40
55
  Guide: [Styling screens](../../docs/app/styling.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octane-xplat/bamboo",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Bamboo CSS integration defaults for Octane xplat apps",
5
5
  "keywords": [
6
6
  "bamboo",
@@ -17,13 +17,25 @@
17
17
  "directory": "packages/bamboo"
18
18
  },
19
19
  "files": [
20
- "src"
20
+ "src",
21
+ "types",
22
+ "!src/**/*.test.*",
23
+ "!src/**/*.spec.*"
21
24
  ],
22
25
  "type": "module",
23
26
  "exports": {
24
- ".": "./src/config.ts",
25
- "./config": "./src/config.ts",
26
- "./vite": "./src/vite.ts"
27
+ ".": {
28
+ "types": "./types/generated/config.d.ts",
29
+ "default": "./src/config.ts"
30
+ },
31
+ "./config": {
32
+ "types": "./types/generated/config.d.ts",
33
+ "default": "./src/config.ts"
34
+ },
35
+ "./vite": {
36
+ "types": "./types/generated/vite.d.ts",
37
+ "default": "./src/vite.ts"
38
+ }
27
39
  },
28
40
  "publishConfig": {
29
41
  "access": "public"
@@ -31,9 +43,21 @@
31
43
  "dependencies": {
32
44
  "@bamboocss/preset-base": "1.56.2",
33
45
  "@bamboocss/types": "1.56.2",
34
- "@bamboocss/vite": "1.56.2"
46
+ "@bamboocss/vite": "1.56.2",
47
+ "magic-string": "0.30.21",
48
+ "@ampproject/remapping": "2.3.0"
49
+ },
50
+ "devDependencies": {
51
+ "typescript": "5.9.3",
52
+ "@bamboocss/dev": "1.56.2",
53
+ "@octane-xplat/cli": "0.16.0"
35
54
  },
36
55
  "peerDependencies": {
37
56
  "vite": ">=5"
57
+ },
58
+ "scripts": {
59
+ "test:packed": "node tests/packed-consumer.mjs",
60
+ "typegen": "tsc -p tsconfig.types.json",
61
+ "test": "node --test tests/platform.test.mjs"
38
62
  }
39
63
  }
package/src/config.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { preset as presetBase } from '@bamboocss/preset-base'
2
2
  import type { Preset, Theme, UserConfig, UtilityConfig } from '@bamboocss/types'
3
3
 
4
+ // Bamboo 1.56.2 has no flexWrap utility. Keep it outside this selected subset
5
+ // rather than promising a utility that cannot be generated.
4
6
  const portableProperties = [
5
7
  'alignItems',
6
8
  'alignSelf',
@@ -13,7 +15,6 @@ const portableProperties = [
13
15
  'flexDirection',
14
16
  'flexGrow',
15
17
  'flexShrink',
16
- 'flexWrap',
17
18
  'fontFamily',
18
19
  'fontSize',
19
20
  'fontWeight',
@@ -52,15 +53,17 @@ const radii = Object.fromEntries(
52
53
  )
53
54
 
54
55
  const portableUtilities = Object.fromEntries(
55
- portableProperties.flatMap((property) => {
56
+ portableProperties.map((property) => {
56
57
  const config = presetBase.utilities[property]
57
58
  if (!config) {
58
- return []
59
+ throw new Error(
60
+ `@octane-xplat/bamboo: missing portable utility "${property}" in @bamboocss/preset-base`,
61
+ )
59
62
  }
60
63
 
61
64
  // Bamboo's default margin scale includes `auto`, which NativeScript
62
65
  // ignores; expose token spacing only in the shared preset.
63
- return [[property, property.startsWith('margin') ? { ...config, values: 'spacing' } : config]]
66
+ return [property, property.startsWith('margin') ? { ...config, values: 'spacing' } : config]
64
67
  }),
65
68
  ) as UtilityConfig
66
69
 
@@ -72,6 +75,21 @@ const portableTheme = {
72
75
  },
73
76
  } satisfies Theme
74
77
 
78
+ // Compile through the framework CSS pipeline, rather than adding runtime
79
+ // ancestor selectors or selector specificity. These names also generate types.
80
+ const platformConditions = {
81
+ web: '@platform web',
82
+ mobile: '@platform mobile',
83
+ native: '@platform native',
84
+ ios: '@platform ios',
85
+ android: '@platform android',
86
+ visionos: '@platform visionos',
87
+ macos: '@platform macos',
88
+ windows: '@platform windows',
89
+ linux: '@platform linux',
90
+ gtk: '@platform gtk',
91
+ }
92
+
75
93
  /**
76
94
  * Utilities and tokens selected for the CSS subset shared by NativeScript and
77
95
  * browsers. This intentionally omits Bamboo's full browser-oriented preset;
@@ -79,6 +97,7 @@ const portableTheme = {
79
97
  */
80
98
  export const xplatPortablePreset: Preset = {
81
99
  name: '@octane-xplat/bamboo/portable',
100
+ conditions: platformConditions,
82
101
  utilities: portableUtilities,
83
102
  theme: portableTheme,
84
103
  }
@@ -92,6 +111,7 @@ export const xplatPortablePreset: Preset = {
92
111
  */
93
112
  export const xplatBambooConfig = {
94
113
  preflight: false,
114
+ conditions: platformConditions,
95
115
  cssVarRoot: ':root, .ns-root',
96
116
  layers: {
97
117
  reset: 'xplat.reset',
@@ -105,5 +125,5 @@ export const xplatBambooConfig = {
105
125
  theme: portableTheme,
106
126
  } satisfies Pick<
107
127
  UserConfig,
108
- 'preflight' | 'cssVarRoot' | 'layers' | 'presets' | 'utilities' | 'theme'
128
+ 'conditions' | 'preflight' | 'cssVarRoot' | 'layers' | 'presets' | 'utilities' | 'theme'
109
129
  >
@@ -0,0 +1,212 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { posix } from 'node:path'
3
+ import MagicString from 'magic-string'
4
+ import remapping from '@ampproject/remapping'
5
+ import type { Plugin } from 'vite'
6
+
7
+ interface PlatformCssApi {
8
+ defer(id: string): void
9
+ filter(css: string, from?: string): string
10
+ project(css: string, from: string, previousMap?: string): { css: string; map?: string }
11
+ }
12
+
13
+ /** Filter only after Bamboo's validation and restore content-addressed asset names. */
14
+ export function platformOutput(): Plugin {
15
+ let compiler: PlatformCssApi | undefined
16
+ let ssr = false
17
+ const adapted = new WeakSet<Plugin>()
18
+ return {
19
+ name: 'xplat-bamboo:platform-output',
20
+ enforce: 'post',
21
+ configResolved(config) {
22
+ ssr = Boolean(config.build.ssr)
23
+ compiler = config.plugins.find((plugin) => plugin.name === 'xplat-platform-css')?.api
24
+ if (config.command === 'build') {
25
+ compiler?.defer('virtual:bamboo.css')
26
+ }
27
+ },
28
+ transform: {
29
+ order: 'pre',
30
+ handler(code, id) {
31
+ if (!id.split('?')[0].endsWith('virtual:bamboo.css') || !code.includes('@platform')) {
32
+ return
33
+ }
34
+ if (!compiler) {
35
+ this.error(
36
+ '@octane-xplat/bamboo: platform conditions require xplatCss(target) from @octane-xplat/cli/vite',
37
+ )
38
+ }
39
+ if (ssr || this.environment?.config.build.ssr) {
40
+ this.error(
41
+ '@octane-xplat/bamboo: platform conditions currently require a single renderer build; SSR generation is not supported',
42
+ )
43
+ }
44
+ },
45
+ },
46
+ options: {
47
+ order: 'post',
48
+ handler(input) {
49
+ const outputs = (
50
+ input as typeof input & { output?: { plugins?: Plugin[] } | { plugins?: Plugin[] }[] }
51
+ ).output
52
+ for (const output of Array.isArray(outputs) ? outputs : outputs ? [outputs] : []) {
53
+ for (const plugin of (output.plugins ?? []).flat(Infinity) as Plugin[]) {
54
+ if (!plugin?.name?.startsWith('bamboocss:output-finalizer:') || adapted.has(plugin)) {
55
+ continue
56
+ }
57
+
58
+ const hook = plugin.generateBundle
59
+ const handler = typeof hook === 'function' ? hook : hook?.handler
60
+ if (!handler) {
61
+ throw new Error(
62
+ '@octane-xplat/bamboo: output finalizer has no generateBundle handler',
63
+ )
64
+ }
65
+
66
+ plugin.generateBundle = {
67
+ ...(typeof hook === 'object' ? hook : {}),
68
+ async handler(options, bundle, isWrite) {
69
+ await handler.call(this, options, bundle, isWrite)
70
+ if (!compiler) {
71
+ return
72
+ }
73
+ const renamed = new Map<string, string>()
74
+ for (const [key, asset] of Object.entries(bundle)) {
75
+ if (asset.type !== 'asset' || !asset.fileName.endsWith('.css')) {
76
+ continue
77
+ }
78
+
79
+ const source =
80
+ typeof asset.source === 'string'
81
+ ? asset.source
82
+ : new TextDecoder().decode(asset.source)
83
+
84
+ const mapKey = `${asset.fileName}.map`
85
+ const mapAsset = bundle[mapKey]
86
+ const previousMap =
87
+ mapAsset?.type === 'asset' ? String(mapAsset.source) : undefined
88
+
89
+ if (!source.includes('@platform')) {
90
+ continue
91
+ }
92
+
93
+ const projected = compiler.project(source, asset.fileName, previousMap)
94
+ let filtered = projected.css
95
+ if (filtered === source) {
96
+ continue
97
+ }
98
+
99
+ const hash = createHash('sha256').update(filtered).digest('hex').slice(0, 16)
100
+ const next = asset.fileName.replace(/\.css$/, `.platform-${hash}.css`)
101
+ renamed.set(asset.fileName, next)
102
+ if (projected.map && previousMap) {
103
+ const nextMap = `${next}.map`
104
+ const map = JSON.parse(projected.map)
105
+ map.file = posix.basename(next)
106
+ this.emitFile({ type: 'asset', fileName: nextMap, source: JSON.stringify(map) })
107
+ delete bundle[mapKey]
108
+ filtered += `
109
+ /*# sourceMappingURL=${posix.basename(nextMap)} */`
110
+ }
111
+
112
+ this.emitFile({ type: 'asset', fileName: next, source: filtered })
113
+ delete bundle[key]
114
+ }
115
+ for (const file of Object.values(bundle)) {
116
+ const replace = (text: string) => {
117
+ for (const [old, next] of renamed) {
118
+ text = text.split(old).join(next)
119
+ const directory = posix.dirname(file.fileName)
120
+ text = text
121
+ .split(posix.relative(directory, old))
122
+ .join(posix.relative(directory, next))
123
+ }
124
+ return text
125
+ }
126
+
127
+ if (file.type === 'chunk') {
128
+ const nextCode = replace(file.code)
129
+ if (nextCode !== file.code) {
130
+ const magic = new MagicString(file.code)
131
+ const replacements = new Map(renamed)
132
+ for (const [old, next] of renamed) {
133
+ replacements.set(
134
+ posix.relative(posix.dirname(file.fileName), old),
135
+ posix.relative(posix.dirname(file.fileName), next),
136
+ )
137
+ }
138
+
139
+ // Scan the original code once so overlapping full/relative names
140
+ // cannot apply two edits to the same source-map span.
141
+ for (let index = 0; index < file.code.length; index++) {
142
+ const found = [...replacements].find(([old]) =>
143
+ file.code.startsWith(old, index),
144
+ )
145
+
146
+ if (!found) {
147
+ continue
148
+ }
149
+
150
+ magic.overwrite(index, index + found[0].length, found[1])
151
+ index += found[0].length - 1
152
+ }
153
+
154
+ file.code = magic.toString()
155
+ if (file.map) {
156
+ const combined = remapping(
157
+ [
158
+ magic.generateMap({ source: file.fileName, hires: 'boundary' }),
159
+ file.map,
160
+ ] as never,
161
+ () => null,
162
+ )
163
+
164
+ const encoded = combined.toString()
165
+ file.map = Object.assign(combined, {
166
+ toUrl: () =>
167
+ `data:application/json;charset=utf-8;base64,${Buffer.from(encoded).toString('base64')}`,
168
+ }) as typeof file.map
169
+
170
+ const mapFile = bundle[`${file.fileName}.map`]
171
+ if (mapFile?.type === 'asset') {
172
+ mapFile.source = encoded
173
+ }
174
+
175
+ if (file.code.includes('//# sourceMappingURL=data:')) {
176
+ file.code =
177
+ file.code.replace(
178
+ /\n?\/\/# sourceMappingURL=data:application\/json[^\n]*$/,
179
+ '',
180
+ ) +
181
+ `
182
+ //# sourceMappingURL=${file.map.toUrl()}`
183
+ }
184
+ }
185
+ }
186
+
187
+ const refs = file as typeof file & { referencedFiles?: string[] }
188
+ if (refs.referencedFiles) {
189
+ refs.referencedFiles = refs.referencedFiles.map(replace)
190
+ }
191
+
192
+ const metadata = (
193
+ file as typeof file & { viteMetadata?: { importedCss?: Set<string> } }
194
+ ).viteMetadata
195
+
196
+ if (metadata?.importedCss) {
197
+ metadata.importedCss = new Set([...metadata.importedCss].map(replace))
198
+ }
199
+ } else if (typeof file.source === 'string') {
200
+ file.source = replace(file.source)
201
+ }
202
+ }
203
+ },
204
+ }
205
+
206
+ adapted.add(plugin)
207
+ }
208
+ }
209
+ },
210
+ },
211
+ }
212
+ }
package/src/vite.ts CHANGED
@@ -1,4 +1,19 @@
1
1
  import { bamboocss, type BambooVitePluginOptions } from '@bamboocss/vite'
2
+ import type { Plugin } from 'vite'
3
+ import { platformOutput } from './platform-output.ts'
4
+
5
+ function runBeforeNativeCss(plugin: Plugin | undefined, anchor: string) {
6
+ const hook = plugin?.generateBundle
7
+ if (plugin && typeof hook === 'function') {
8
+ plugin.generateBundle = { order: 'pre', handler: hook }
9
+ } else if (hook && typeof hook === 'object' && typeof hook.handler === 'function') {
10
+ hook.order = 'pre'
11
+ } else {
12
+ throw new Error(
13
+ `@octane-xplat/bamboo: native CSS adaptation requires ${anchor} with a generateBundle handler`,
14
+ )
15
+ }
16
+ }
2
17
 
3
18
  export interface XplatBambooOptions extends BambooVitePluginOptions {
4
19
  /** NativeScript consumes CSS assets in its own generateBundle hook. */
@@ -18,13 +33,28 @@ export function xplatBamboo({ native = false, ...options }: XplatBambooOptions =
18
33
  // Let Bamboo prune and validate the emitted asset before NativeScript's
19
34
  // main-entry hook serializes it into the native bootstrap and removes it.
20
35
  const cssPlugin = plugins.find((plugin) => plugin.name === 'bamboocss:css')
21
- if (cssPlugin && typeof cssPlugin.generateBundle === 'object') {
22
- cssPlugin.generateBundle.order = 'pre'
23
- }
36
+ runBeforeNativeCss(cssPlugin, 'bamboocss:css')
24
37
 
38
+ let isBuild = false
25
39
  plugins.push({
26
40
  name: 'xplat-bamboo:nativescript-entry-graph',
27
41
  enforce: 'post',
42
+ configResolved(config) {
43
+ isBuild = config.command === 'build'
44
+ },
45
+ buildEnd(error) {
46
+ if (!isBuild || error) {
47
+ return
48
+ }
49
+
50
+ // Inspect the graph, including cached modules in watch builds. A
51
+ // custom entry that already imports the sheet needs no injection.
52
+ if (![...this.getModuleIds()].some((id) => id.split('?')[0] === '\0virtual:bamboo.css')) {
53
+ this.error(
54
+ '@octane-xplat/bamboo: native entry graph is missing virtual:bamboo.css; expected virtual:entry-with-polyfills or an explicit stylesheet import',
55
+ )
56
+ }
57
+ },
28
58
  transform(code, id) {
29
59
  // @nativescript/vite builds from a generated entry
30
60
  // (`virtual:entry-with-polyfills`). Under HMR that entry boots
@@ -49,13 +79,8 @@ export function xplatBamboo({ native = false, ...options }: XplatBambooOptions =
49
79
  options: {
50
80
  order: 'post',
51
81
  handler(inputOptions) {
52
- type OutputHook = {
53
- name?: string
54
- generateBundle?: { order?: string } | ((...args: never[]) => unknown)
55
- }
56
-
57
- const options = inputOptions as unknown as {
58
- output?: { plugins?: OutputHook[] } | Array<{ plugins?: OutputHook[] }>
82
+ const options = inputOptions as typeof inputOptions & {
83
+ output?: { plugins?: Plugin[] } | Array<{ plugins?: Plugin[] }>
59
84
  }
60
85
 
61
86
  const outputs = Array.isArray(options.output)
@@ -64,14 +89,23 @@ export function xplatBamboo({ native = false, ...options }: XplatBambooOptions =
64
89
  ? [options.output]
65
90
  : []
66
91
 
92
+ // Upstream installs one finalizer per configured output. With no
93
+ // output configured its options hook deliberately installs none.
67
94
  for (const output of outputs) {
68
- for (const plugin of output.plugins ?? []) {
69
- if (
70
- plugin.name?.startsWith('bamboocss:output-finalizer:') &&
71
- typeof plugin.generateBundle === 'object'
72
- ) {
73
- plugin.generateBundle.order = 'pre'
74
- }
95
+ const finalizers = (output.plugins ?? [])
96
+ .flat(Infinity)
97
+ .filter((plugin): plugin is Plugin =>
98
+ Boolean(plugin && plugin.name?.startsWith('bamboocss:output-finalizer:')),
99
+ )
100
+
101
+ if (!finalizers.length) {
102
+ throw new Error(
103
+ '@octane-xplat/bamboo: native CSS adaptation requires a bamboocss:output-finalizer:* plugin for each configured output',
104
+ )
105
+ }
106
+
107
+ for (const finalizer of finalizers) {
108
+ runBeforeNativeCss(finalizer, finalizer.name)
75
109
  }
76
110
  }
77
111
  },
@@ -79,5 +113,6 @@ export function xplatBamboo({ native = false, ...options }: XplatBambooOptions =
79
113
  })
80
114
  }
81
115
 
116
+ plugins.push(platformOutput())
82
117
  return plugins
83
118
  }
@@ -0,0 +1,58 @@
1
+ import type { Preset, UtilityConfig } from '@bamboocss/types';
2
+ /**
3
+ * Utilities and tokens selected for the CSS subset shared by NativeScript and
4
+ * browsers. This intentionally omits Bamboo's full browser-oriented preset;
5
+ * apps can extend it when they have checked a property on their targets.
6
+ */
7
+ export declare const xplatPortablePreset: Preset;
8
+ /**
9
+ * Bamboo defaults for apps using the shared Octane xplat stylesheet.
10
+ *
11
+ * Pass this object to `defineConfig` from `@bamboocss/dev`, then add the app's
12
+ * `include` and `outdir`. The shared UI stylesheet declares the matching layer
13
+ * order before `virtual:bamboo.css` is imported.
14
+ */
15
+ export declare const xplatBambooConfig: {
16
+ preflight: false;
17
+ conditions: {
18
+ web: string;
19
+ mobile: string;
20
+ native: string;
21
+ ios: string;
22
+ android: string;
23
+ visionos: string;
24
+ macos: string;
25
+ windows: string;
26
+ linux: string;
27
+ gtk: string;
28
+ };
29
+ cssVarRoot: string;
30
+ layers: {
31
+ reset: string;
32
+ base: string;
33
+ tokens: string;
34
+ recipes: string;
35
+ utilities: string;
36
+ };
37
+ presets: never[];
38
+ utilities: UtilityConfig;
39
+ theme: {
40
+ tokens: {
41
+ colors: {
42
+ [k: string]: {
43
+ value: string;
44
+ };
45
+ };
46
+ radii: {
47
+ [k: string]: {
48
+ value: string;
49
+ };
50
+ };
51
+ spacing: {
52
+ [k: string]: {
53
+ value: string;
54
+ };
55
+ };
56
+ };
57
+ };
58
+ };
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'vite';
2
+ /** Filter only after Bamboo's validation and restore content-addressed asset names. */
3
+ export declare function platformOutput(): Plugin;
@@ -0,0 +1,13 @@
1
+ import { type BambooVitePluginOptions } from '@bamboocss/vite';
2
+ import type { Plugin } from 'vite';
3
+ export interface XplatBambooOptions extends BambooVitePluginOptions {
4
+ /** NativeScript consumes CSS assets in its own generateBundle hook. */
5
+ native?: boolean;
6
+ }
7
+ /**
8
+ * Create Bamboo's Vite plugins for an Octane xplat app.
9
+ *
10
+ * Pass `cwd` and `configPath` when Bamboo's source/config root differs from
11
+ * Vite's app root, as it does in the shared harness.
12
+ */
13
+ export declare function xplatBamboo({ native, ...options }?: XplatBambooOptions): Plugin<any>[];